Skip to content

Commit d4e81a9

Browse files
authored
Merge pull request #1393 from nishant0708/Q617
[Feature Request]: Leetcode Q617 #1342
2 parents 5f75314 + 80b6d60 commit d4e81a9

File tree

1 file changed

+135
-0
lines changed

1 file changed

+135
-0
lines changed
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
---
2+
id: merge-two-binary-trees
3+
title: Merge Two Binary Trees
4+
sidebar_label: 0617-Merge-Two-Binary-Trees
5+
tags:
6+
- Tree
7+
- Depth-First Search
8+
- Breadth-First Search
9+
description: "Given two binary trees, merge them into a new binary tree by adding the values of overlapping nodes."
10+
---
11+
12+
## Problem
13+
14+
You are given two binary trees `root1` and `root2`. 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 the two trees 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 the new tree.
15+
16+
### Examples
17+
18+
**Example 1:**
19+
20+
**Input:** `root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]`
21+
**Output:** `[3,4,5,5,4,null,7]`
22+
23+
**Example 2:**
24+
25+
**Input:** `root1 = [1], root2 = [1,2]`
26+
**Output:** `[2,2]`
27+
28+
### Constraints
29+
30+
- The number of nodes in both trees is in the range `[0, 2000]`.
31+
- `-10^4 <= Node.val <= 10^4`
32+
33+
---
34+
35+
## Approach
36+
37+
To solve this problem, we can use a recursive depth-first search (DFS) approach. The idea is to traverse both trees simultaneously and sum the values of overlapping nodes.
38+
39+
### Steps:
40+
41+
1. **Base Case:** If both nodes are `null`, return `null`.
42+
2. If one of the nodes is `null`, return the other node.
43+
3. Create a new tree node with the sum of the values of the overlapping nodes.
44+
4. Recursively merge the left children.
45+
5. Recursively merge the right children.
46+
6. Return the merged tree.
47+
48+
### Solution
49+
50+
#### Java
51+
52+
```java
53+
/**
54+
* Definition for a binary tree node.
55+
* public class TreeNode {
56+
* int val;
57+
* TreeNode left;
58+
* TreeNode right;
59+
* TreeNode(int x) { val = x; }
60+
* }
61+
*/
62+
class Solution {
63+
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
64+
if (root1 == null) {
65+
return root2;
66+
}
67+
if (root2 == null) {
68+
return root1;
69+
}
70+
TreeNode merged = new TreeNode(root1.val + root2.val);
71+
merged.left = mergeTrees(root1.left, root2.left);
72+
merged.right = mergeTrees(root1.right, root2.right);
73+
return merged;
74+
}
75+
}
76+
```
77+
#### C++
78+
79+
```cpp
80+
/**
81+
* Definition for a binary tree node.
82+
* struct TreeNode {
83+
* int val;
84+
* TreeNode *left;
85+
* TreeNode *right;
86+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
87+
* };
88+
*/
89+
class Solution {
90+
public:
91+
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
92+
if (root1 == nullptr) {
93+
return root2;
94+
}
95+
if (root2 == nullptr) {
96+
return root1;
97+
}
98+
TreeNode* merged = new TreeNode(root1->val + root2->val);
99+
merged->left = mergeTrees(root1->left, root2->left);
100+
merged->right = mergeTrees(root1->right, root2->right);
101+
return merged;
102+
}
103+
};
104+
```
105+
106+
#### Python
107+
108+
```python
109+
# Definition for a binary tree node.
110+
class TreeNode:
111+
def __init__(self, val=0, left=None, right=None):
112+
self.val = val
113+
self.left = left
114+
self.right = right
115+
116+
class Solution:
117+
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
118+
if not root1:
119+
return root2
120+
if not root2:
121+
return root1
122+
merged = TreeNode(root1.val + root2.val)
123+
merged.left = self.mergeTrees(root1.left, root2.left)
124+
merged.right = self.mergeTrees(root1.right, root2.right)
125+
return merged
126+
```
127+
### Complexity Analysis
128+
**Time Complexity:** O(n)
129+
>Reason: The algorithm visits each node in the tree once, where n is the total number of nodes in both trees combined.
130+
131+
**Space Complexity:** O(h)
132+
>Reason: The space complexity is determined by the height h of the tree due to the recursion stack. In the worst case, the height of the tree is O(n) for a skewed tree, but O(log n) for a balanced tree.
133+
134+
### References
135+
**LeetCode Problem:** Merge Two Binary Trees

0 commit comments

Comments
 (0)