Created
November 23, 2019 12:58
-
-
Save zack-w/9b6641d01de827010561a3e80c92542a 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
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { | |
if(t1==null) return t2; | |
if(t2==null) return t1; | |
//use st1 for t1 and st2 for t2. You can use one stack as well where you store pairs | |
Stack<TreeNode> st1 = new Stack<>(); | |
Stack<TreeNode> st2 = new Stack<>(); | |
//invariant: neither n1 or n2 can be null | |
st1.push(t1); | |
st2.push(t2); | |
while(!st1.isEmpty()&&!st2.isEmpty()) | |
{ | |
TreeNode n1 = st1.pop(); | |
TreeNode n2 = st2.pop(); | |
n1.val+=n2.val; | |
//handle left subtree | |
if(n1.left==null) | |
{ | |
n1.left = n2.left; | |
} | |
else if(n2.left!=null) //keep the invariant | |
{ | |
st1.push(n1.left); | |
st2.push(n2.left); | |
} | |
//handle right subtree | |
if(n1.right==null) | |
{ | |
n1.right = n2.right; | |
} | |
else if(n2.right!=null) //keep the invariant | |
{ | |
st1.push(n1.right); | |
st2.push(n2.right); | |
} | |
} | |
return t1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment