Last active
December 10, 2018 21:19
-
-
Save antonlogvinenko/88298579e41aeeda6560fab0fc8caa98 to your computer and use it in GitHub Desktop.
merging trees: iterative using stack, immutable trees
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(int x) { val = x; } | |
* } | |
*/ | |
class Solution { | |
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { | |
Stack<TreeNode> stack = new Stack<>(); | |
TreeNode result = new TreeNode(0); | |
if (t1 == null && t2 == null) | |
return null; | |
if (t1 == null) | |
return t2; | |
if (t2 == null) | |
return t1; | |
stack.push(result); | |
stack.push(t1); | |
stack.push(t2); | |
while (!stack.isEmpty()) { | |
TreeNode p2 = stack.pop(); | |
TreeNode p1 = stack.pop(); | |
TreeNode p = stack.pop(); | |
p.val = p1.val + p2.val; | |
if (p1.left != null || p2.left != null) { | |
if (p1.left == null) { | |
p.left = p2.left; | |
} else if (p2.left == null) { | |
p.left = p1.left; | |
} else { | |
TreeNode left = new TreeNode(0); | |
p.left = left; | |
stack.push(p.left); | |
stack.push(p1.left); | |
stack.push(p2.left); | |
} | |
} | |
if (p1.right != null || p2.right != null) { | |
if (p1.right == null) { | |
p.right = p2.right; | |
} else if (p2.right == null) { | |
p.right = p1.right; | |
} else { | |
TreeNode right = new TreeNode(0); | |
p.right = right; | |
stack.push(p.right); | |
stack.push(p1.right); | |
stack.push(p2.right); | |
} | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment