Created
August 4, 2021 06:01
-
-
Save aflah02/58a62371c454bc56d2c569b3edec74bf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode() {} | |
* TreeNode(int val) { this.val = val; } | |
* TreeNode(int val, TreeNode left, TreeNode right) { | |
* this.val = val; | |
* this.left = left; | |
* this.right = right; | |
* } | |
* } | |
*/ | |
class Solution { | |
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { | |
if (root1 == null && root2 == null){ | |
return null; | |
} | |
TreeNode root = new TreeNode(); | |
if (root1 == null){ | |
root.val = root2.val; | |
} | |
else if (root2 == null){ | |
root.val = root1.val; | |
} | |
else{ | |
root.val = root1.val + root2.val; | |
} | |
if (root1.left != null && root2.left != null){ | |
root.left = mergeTrees(root1.left, root2.left); | |
} | |
else if (root1.left != null && root2.left == null){ | |
root.left = mergeTrees(root1.left, null); | |
} | |
else if (root1.left == null && root2.left != null){ | |
root.left = mergeTrees(null, root2.left); | |
} | |
else{ | |
root.left = mergeTrees(null, null); | |
} | |
if (root1.right != null && root2.right != null){ | |
root.right = mergeTrees(root1.right, root2.right); | |
} | |
else if (root1.right != null && root2.right == null){ | |
root.right = mergeTrees(root1.right, null); | |
} | |
else if (root1.right == null && root2.right != null){ | |
root.right = mergeTrees(null, root2.right);; | |
} | |
else{ | |
root.right = mergeTrees(null, null); | |
} | |
return root; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment