Skip to content

Commit d1b210e

Browse files
authored
Merge pull request neetcode-gh#1479 from nutandevjoshi/617-Merge-Two-Binary-Trees
617. Merge Two Binary Trees
2 parents 55a1577 + 0facc21 commit d1b210e

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {TreeNode} root1
3+
* @param {TreeNode} root2
4+
* @return {TreeNode}
5+
* Time complexity = O(n+m)
6+
*/
7+
var mergeTrees = function(root1, root2) {
8+
// Base case to return null as result of having both root1, root2 null
9+
if(!root1 && !root2) {
10+
return null;
11+
}
12+
13+
const val1 = root1 ? root1.val : 0;
14+
const val2 = root2 ? root2.val : 0;
15+
16+
const root = new TreeNode(val1+val2);
17+
root.left = mergeTrees(root1 ? root1.left : null, root2 ? root2.left: null);
18+
root.right = mergeTrees(root1 ? root1.right : null , root2 ? root2.right: null);
19+
return root;
20+
};

0 commit comments

Comments
 (0)