617. Merge Two Binary Trees
https://leetcode.com/problems/merge-two-binary-trees/
---
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7
Note: The merging process must start from the root nodes of both trees.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode() {} | |
* TreeNode(int val) { this.val = val; } | |
* TreeNode(int val, TreeNode left, TreeNode right) { | |
* this.val = val; | |
* this.left = left; | |
* this.right = right; | |
* } | |
* } | |
*/ | |
class Solution { | |
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { | |
if (t1 == null || t2 == null) { | |
return t1 == null ? t2 : t1; | |
} | |
TreeNode ans = new TreeNode(); | |
ans.val = (t1 == null ? 0 : t1.val) + (t2 == null ? 0 : t2.val); | |
ans.left = mergeTrees(t1 == null ? t1 : t1.left, t2 == null ? t2 : t2.left); | |
ans.right = mergeTrees(t1 == null ? t1 : t1.right, t2 == null ? t2 : t2.right); | |
return ans; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Definition for a binary tree node. | |
# class TreeNode: | |
# def __init__(self, val=0, left=None, right=None): | |
# self.val = val | |
# self.left = left | |
# self.right = right | |
class Solution: | |
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]: | |
def dfs(node1: TreeNode, node2: TreeNode) -> Optional[TreeNode]: | |
if node1 and node2: | |
node = TreeNode(node1.val + node2.val) | |
node.left = dfs(node1.left, node2.left) | |
node.right = dfs(node1.right, node2.right) | |
return node | |
else: | |
return node1 or node2 | |
return dfs(root1, root2) |