[LeetCode][617. Merge Two Binary Trees] 4 Approaches: Recursion, Iteration, BFS and DFS
By Long Luo
This article is the solution 4 Approaches: Recursion, Iteration, BFS and DFS of Problem 617. Merge Two Binary Trees .
Here are 4 approaches to solve this problem in Java: Recursion, Iteration, BFS and DFS.
Recursion
Method 1: New Tree
We can create a new Tree, each \(\texttt{TreeNode}\) value is sum of two nodes.1
2
3
4
5
6
7
8
9
10
11
12public static TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) {
return root2;
}
if (root2 == null) {
return root1;
}
TreeNode merged = new TreeNode(root1.val + root2.val);
merged.left = mergeTrees(root1.left, root2.left);
merged.right = mergeTrees(root1.right, root2.right);
return merged;
}
Analysis
- Time Complexity: \(O(min(m, n))\)
- Space Complexity: \(O(min(m, n))\)
Method 2
Traverse both the given trees in a PreOrder style.
At every step, check if the current node exists for both the trees. If one of these children happens to be null, we return the child of the other tree to be added as a child subtree to the calling parent node in the first tree.
We can add the values in the current nodes of both the trees and update the value in the current node of the first tree to reflect this sum obtained.
Then we call the \(\texttt{mergeTrees()}\) with the left children and then with the right children of the current nodes of the two trees.
At the end, the first tree will represent the required resultant merged binary tree.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16public static TreeNode mergeTrees_rec(TreeNode root1, TreeNode root2) {
if (root1 == null) {
return root2;
}
if (root2 == null) {
return root1;
}
if (root1 != null) {
root1.val += root2.val;
root1.left = mergeTrees_rec(root1.left, root2.left);
root1.right = mergeTrees_rec(root1.right, root2.right);
}
return root1;
}
Analysis
- Time Complexity: \(O(min(m, n))\)
- Space Complexity: \(O(min(m, n))\)