Leetcode 617. Merge Two Binary Trees
Problem Explanation:
We are given two binary trees. Some of the nodes in these trees might overlap. We need to merge these two trees into a new binary tree. If two nodes overlap, we sum their values and put the sum as the new value for the merged node. If there is no overlapping node, we use the non-null node as the node for the new tree. The merging process should be started from the root nodes of both trees.
Example:
Input:
Tree 1 Tree 2
1 2
/ \ /
3 2 1 3
/ \
5 4 7
Output:
Merged tree:
3
/
4 5
/ \
5 4 7
Solution Explanation:
The approach for the solution is using recursion.
- First, we check if both root nodes for the two provided trees are null. If yes, then we return null because null nodes can not be merged.
- If only one of the roots is null, we pass the non-null child to the next recursion.
- If both roots are not null we create a new node for the resulting tree. Its value will be the sum of the two overlapping nodes.
We then recurringly call the same function for the left and right child nodes of the two roots and assign the result to the left and right child of the newly created node.
Finally, we return the new node as the result of the merge operation.
Python Solution
1 2python 3class TreeNode: 4 def __init__(self, x): 5 self.val = x 6 self.left = None 7 self.right = None 8 9 10class Solution: 11 def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: 12 if root1 is None and root2 is None: 13 return None 14 val = 0 15 if root1 is not None: 16 val += root1.val 17 if root2 is not None: 18 val += root2.val 19 20 node = TreeNode(val) 21 node.left = self.mergeTrees(root1.left if root1 is not None else None, root2.left if root2 is not None else None) 22 node.right = self.mergeTrees(root1.right if root1 is not None else None, root2.right if root2 is not None else None) 23 24 return node
Java Solution
1
2java
3public class TreeNode {
4 int val;
5 TreeNode left;
6 TreeNode right;
7 TreeNode(int x) { val = x; }
8}
9
10public class Solution {
11 public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
12 if (root1 == null && root2 == null) {
13 return null;
14 }
15
16 int val = (root1 == null ? 0 : root1.val) + (root2 == null ? 0 : root2.val);
17 TreeNode node = new TreeNode(val);
18 node.left = mergeTrees(root1 == null ? null : root1.left, root2 == null ? null : root2.left);
19 node.right = mergeTrees(root1 == null ? null : root1.right, root2 == null ? null : root2.right);
20
21 return node;
22 }
23}
JavaScript Solution
1
2javascript
3function TreeNode(val, left, right) {
4 this.val = (val === undefined ? 0 : val);
5 this.left = (left === undefined ? null : left);
6 this.right = (right === undefined ? null : right);
7}
8
9var mergeTrees = function(root1, root2) {
10 if (root1 === null && root2 === null) {
11 return null;
12 }
13
14 let val = (root1 === null ? 0 : root1.val) + (root2 === null ? 0 : root2.val);
15 let node = new TreeNode(val);
16 node.left = mergeTrees(root1 === null ? null : root1.left, root2 === null ? null : root2.left);
17 node.right = mergeTrees(root1 === null ? null : root1.right, root2 === null ? null : root2.right);
18
19 return node;
20};
C++ Solution
1
2cpp
3class TreeNode {
4 public:
5 int val;
6 TreeNode *left;
7 TreeNode *right;
8 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
9};
10
11class Solution {
12 public:
13 TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
14 if (root1 == NULL && root2 == NULL) {
15 return NULL;
16 }
17
18 int val = (root1 == NULL ? 0 : root1->val) + (root2 == NULL ? 0 : root2->val);
19 TreeNode* node = new TreeNode(val);
20 node->left = mergeTrees(root1 == NULL ? NULL : root1->left, root2 == NULL ? NULL : root2->left);
21 node->right = mergeTrees(root1 == NULL ? NULL : root1->right, root2 == NULL ? NULL : root2->right);
22
23 return node;
24 }
25};
C# Solution
1
2csharp
3public class TreeNode {
4 public int val;
5 public TreeNode left;
6 public TreeNode right;
7 public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) {
8 this.val = val;
9 this.left = left;
10 this.right = right;
11 }
12}
13
14public class Solution {
15 public TreeNode MergeTrees(TreeNode root1, TreeNode root2) {
16 if (root1 == null && root2 == null) {
17 return null;
18 }
19
20 int val = (root1 == null ? 0 : root1.val) + (root2 == null ? 0 : root2.val);
21 TreeNode node = new TreeNode(val);
22 node.left = MergeTrees(root1 == null ? null : root1.left, root2 == null ? null : root2.left);
23 node.right = MergeTrees(root1 == null ? null : root1.right, root2 == null ? null : root2.right);
24
25 return node;
26 }
27}
Since we're traversing each node once, the time complexity of this solution is O(N), where N is the smaller number of nodes from the two given trees. The space complexity is O(N) as well because in the worst case, we might need to store all the nodes if every node is a non-null node.# Conclusion
Merging binary trees is a common question asked in computer science interviews, and it can be a bit tricky. Understanding how recursion works is key to solving this problem. Remember that the solution can be achieved by starting the process from the root nodes of both trees and then recursively merging their children nodes.
The above code snippets in Python, JavaScript, Java, C++, and C# can be used to merge binary trees. The time and space complexity of these solutions are both O(N), making them efficient.
Keep practicing with different problems involving binary trees and recursion to solidify the concepts, enabling you to come up with efficient solutions faster. Whether you're practicing for an interview or need to apply these concepts in real projects, understanding the logic behind binary tree operations is crucial.
In practice, such a problem can be handy when one needs to merge two different datasets represented in Tree data structure, whenever data merging is required, for example, in the case of merging two organizational hierarchies or data structures in a computational biology ecosystem. The solutions provided could be extended further in different ways according to the specific requirements of your project.
Got a question?ย Ask the Teaching Assistantย anything you don't understand.
Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.