Skip to content

Commit

Permalink
Added Java 617 Merge Two Binary Trees
Browse files Browse the repository at this point in the history
  • Loading branch information
miladra committed May 20, 2022
1 parent 01a2b36 commit 15795cd
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions java/617-Merge-Two-Binary-Trees.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {

if(root1 == null && root2 == null) return null;

int val1 = root1 != null ? root1.val : 0;
int val2 = root2 != null ? root2.val : 0;

TreeNode root = new TreeNode(val1+val2);

// merge left side of trees if they are not null
root.left = mergeTrees((root1 != null && root1.left != null) ? root1.left : null , (root2 != null && root2.left != null) ? root2.left : null);

// merge righ side of trees if they are not null
root.right = mergeTrees((root1 != null && root1.right != null) ? root1.right : null , (root2 !=null && root2.right != null) ? root2.right: null );

return root;
}
}


0 comments on commit 15795cd

Please sign in to comment.