Skip to content

Commit 0919e8a

Browse files
authored
Add files via upload
1 parent cf85a80 commit 0919e8a

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

MergeBinaryTrees.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
public class MergeBinaryTrees {
2+
3+
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
4+
//assign non null root to head
5+
TreeNode head=root1!=null?root1:root2;
6+
//if either root is null skip merging
7+
if(root1!=null && root2!=null)
8+
merge(root1,root2);
9+
return head;
10+
}
11+
12+
public void merge(TreeNode root1, TreeNode root2) {
13+
//nothing to merge
14+
if(root1==null && root2==null) {
15+
return;
16+
}
17+
//merge both
18+
if(root1!=null && root2!=null) {
19+
root1.val+=root2.val;
20+
}
21+
22+
//if both have left values merge them otherwise assign non null value to the left branch
23+
if(root1.left!=null && root2.left!=null) {
24+
merge(root1.left,root2.left);
25+
}
26+
//if root1 left is null assign root1 left
27+
if(root1.left==null) {
28+
root1.left=root2.left;
29+
}
30+
31+
//if both have right values merge them otherwise assign non null value to the right branch
32+
if(root1.right!=null && root2.right!=null) {
33+
merge(root1.right,root2.right);
34+
}
35+
if(root1.right==null) {
36+
root1.right=root2.right;
37+
}
38+
39+
}
40+
}

0 commit comments

Comments
 (0)