
Problem
Solution
Submissions
Merge Two Binary Trees
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to merge two binary trees. The merging rule is that if two nodes overlap, then sum the node values 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:
- Output:
- Explanation:
- Step 1: Merge the root nodes: 1 + 2 = 3
- Step 2: Merge the left child of the roots: 3 + 1 = 4
- Step 3: Merge the right child of the roots: 2 + 3 = 5
- Step 4: Node with value 5 in Tree 1 has no corresponding node in Tree 2, so it is carried over
- Step 5: Node with value 4 in Tree 2 has no corresponding node in Tree 1, so it is carried over
- Step 6: Node with value 7 in Tree 2 has no corresponding node in Tree 1, so it is carried over
Example 2
- Input:
- Output:
- Explanation:
- Step 1: Merge the root nodes: 1 + 3 = 4
- Step 2: Node with value 2 in Tree 1 has no corresponding node in Tree 2, so it is carried over
- Step 3: Node with value 4 in Tree 2 has no corresponding node in Tree 1, so it is carried over
Constraints
- The number of nodes in both trees is in the range [0, 2000]
- -10^4 ≤ Node.val ≤ 10^4
- The merging process must start from the root nodes of both trees
- Time Complexity: O(n), where n is the number of nodes in the smaller tree
- Space Complexity: O(h), where h is the height of the merged tree
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 exist, sum their values and create a new node with this sum
- Recursively merge the left subtrees and the right subtrees
- If one node is NULL, return the other node (no need to merge further in that direction)
- Build the merged tree during the traversal
- Handle leaf nodes and NULL pointers appropriately