Skip to content

Commit 0facc21

Browse files
committed
617. Merge Two Binary Trees
1 parent 82e9776 commit 0facc21

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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy