Skip to content

Commit 15795cd

Browse files
committed
Added Java 617 Merge Two Binary Trees
1 parent 01a2b36 commit 15795cd

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

java/617-Merge-Two-Binary-Trees.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
3+
4+
if(root1 == null && root2 == null) return null;
5+
6+
int val1 = root1 != null ? root1.val : 0;
7+
int val2 = root2 != null ? root2.val : 0;
8+
9+
TreeNode root = new TreeNode(val1+val2);
10+
11+
// merge left side of trees if they are not null
12+
root.left = mergeTrees((root1 != null && root1.left != null) ? root1.left : null , (root2 != null && root2.left != null) ? root2.left : null);
13+
14+
// merge righ side of trees if they are not null
15+
root.right = mergeTrees((root1 != null && root1.right != null) ? root1.right : null , (root2 !=null && root2.right != null) ? root2.right: null );
16+
17+
return root;
18+
}
19+
}
20+
21+

0 commit comments

Comments
 (0)