
Problem
Solution
Submissions
Merge Two Binary Trees
Certification: Basic Level
Accuracy: 75%
Submissions: 4
Points: 5
Write a Java program to merge two binary trees. The merging rule is that if two nodes overlap, then sum the node values up as the new value of the merged node. Otherwise, the non-null node will be used as the node of the new tree.
Example 1
- Input:
- root1 = [1,3,2,5]
- root2 = [2,1,3,null,4,null,7]
- Output: [3,4,5,5,4,null,7]
- Explanation:
- Merged tree:
- Merging Process:
- Root: 1 + 2 = 3
- Left child: 3 + 1 = 4
- Right child: 2 + 3 = 5
- Left-left: 5 + null = 5
- Left-right: null + 4 = 4
- Right-right: null + 7 = 7
- Merged tree:
Example 2
- Input:
- root1 = [1]
- root2 = [1,2]
- Output: [2,2]
- Explanation:
- Merged tree:
- Merging Process:
- Root: 1 + 1 = 2
- Left child: null + 2 = 2
- Merged tree:
Constraints
- The number of nodes in both trees is in the range [0, 2000].
- -10^4 ≤ Node.val ≤ 10^4
- Time Complexity: O(n), where n is the minimum number of nodes in the two trees.
- Space Complexity: O(h), where h is the height of the trees.
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a recursive approach to traverse both trees simultaneously.
- If both nodes are present, sum their values and create a new node.
- If only one node is present, use that node for the merged tree.
- Recursively merge the left and right subtrees.
- Return the merged tree root.