Given inorder and postorder traversal of a tree, construct the binary tree
https://leetcode.com/discuss/10961/my-recursive-java-code-with-o-n-time-and-o-n-space
X. Iterative Version
https://leetcode.com/discuss/15115/my-comprehension-of-o-n-solution-from-%40hongzhi
https://leetcode.com/discuss/23834/java-iterative-solution-with-explanation
Starting from the last element of the postorder and inorder array, we put elements from postorder array to a stack and each one is the right child of the last one until an element in postorder array is equal to the element on the inorder array. Then, we pop as many as elements we can from the stack and decrease the mark in inorder array until the peek() element is not equal to the mark value or the stack is empty. Then, the new element that we are gonna scan from postorder array is the left child of the last element we have popped out from the stack.
public class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if (inorder == null || inorder.length < 1) return null; int i = inorder.length - 1; int p = i; TreeNode node; TreeNode root = new TreeNode(postorder[postorder.length - 1]); Stack<TreeNode> stack = new Stack<>(); stack.push(root); p--; while (true) { if (inorder[i] == stack.peek().val) { // inorder[i] is on top of stack, pop stack to get its parent to get to left side if (--i < 0) break; node = stack.pop(); if (!stack.isEmpty() && inorder[i] == stack.peek().val) {// continue pop stack to get to left side continue; } node.left = new TreeNode(postorder[p]); stack.push(node.left); } else { // inorder[i] is not on top of stack, postorder[p] must be right child node = new TreeNode(postorder[p]); stack.peek().right = node; stack.push(node); } p--; } return root; } }
https://leetcode.com/discuss/4761/why-my-code-memory-limit-exceeded%EF%BC%9F
Read full article from LeetCode - Construct Binary Tree from Inorder and Postorder Traversal | Darren's Blog
This problem can be illustrated by using a simple example.
in-order: 4 2 5 (1) 6 7 3 8 post-order: 4 5 2 6 7 8 3 (1)
From the post-order array, we know that last element is the root. We can find the root in in-order array. Then we can identify the left and right sub-trees of the root from in-order array.
Using the length of left sub-tree, we can identify left and right sub-trees in post-order array. Recursively, we can build up the tree.
public TreeNode buildTree(int[] inorder, int[] postorder) { int inStart = 0; int inEnd = inorder.length - 1; int postStart = 0; int postEnd = postorder.length - 1; return buildTree(inorder, inStart, inEnd, postorder, postStart, postEnd); } public TreeNode buildTree(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) { if (inStart > inEnd || postStart > postEnd) return null; int rootValue = postorder[postEnd]; TreeNode root = new TreeNode(rootValue); int k = 0; for (int i = 0; i < inorder.length; i++) { if (inorder[i] == rootValue) { k = i; break; } } root.left = buildTree(inorder, inStart, k - 1, postorder, postStart, postStart + k - (inStart + 1)); // Becuase k is not the length, it it need to -(inStart+1) to get the length root.right = buildTree(inorder, k + 1, inEnd, postorder, postStart + k- inStart, postEnd - 1); // postStart+k-inStart = postStart+k-(inStart+1) +1 return root; } |
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (postorder == null || inorder == null ||
postorder.length != inorder.length || postorder.length == 0)
return null;
return recursiveBuildTree(postorder, 0, inorder, 0, postorder.length);
}
private TreeNode recursiveBuildTree(int[] postorder, int postBegin, int[] inorder, int inBegin, int len) {
assert postBegin+len <= postorder.length;
assert inBegin+len <= inorder.length;
if (len <= 0) // Empty tree
return null;
// The beginning node in the preorder traversal is the root
TreeNode root = new TreeNode(postorder[postBegin+len-1]);
// Find the position of the root in the inorder traversal so as to decide the number of nodes
// in its left subtree
int leftTreeLen = 0;
for(; leftTreeLen < len && inorder[inBegin+leftTreeLen] != root.val; leftTreeLen++);
// Recursively build its left subtree and right subtree; note the change in postBegin, inBegin, and len
TreeNode left = recursiveBuildTree(postorder, postBegin, inorder, inBegin, leftTreeLen);
TreeNode right = recursiveBuildTree(postorder, postBegin+leftTreeLen, inorder, inBegin+leftTreeLen+1,
len-leftTreeLen-1);
// Link the left and right subtrees with the root
root.left = left;
root.right = right;
return root;
}
X. Use HashMaphttps://leetcode.com/discuss/10961/my-recursive-java-code-with-o-n-time-and-o-n-space
The the basic idea is to take the last element in postorder array as the root, find the position of the root in the inorder array; then locate the range for left sub-tree and right sub-tree and do recursion. Use a HashMap to record the index of root in the inorder array.
public TreeNode buildTreePostIn(int[] inorder, int[] postorder) { if (inorder == null || postorder == null || inorder.length != postorder.length) return null; HashMap<Integer, Integer> hm = new HashMap<Integer,Integer>(); for (int i=0;i<inorder.length;++i) hm.put(inorder[i], i); return buildTreePostIn(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1,hm); } private TreeNode buildTreePostIn(int[] inorder, int is, int ie, int[] postorder, int ps, int pe, HashMap<Integer,Integer> hm){ if (ps>pe || is>ie) return null; TreeNode root = new TreeNode(postorder[pe]); int ri = hm.get(postorder[pe]); TreeNode leftchild = buildTreePostIn(inorder, is, ri-1, postorder, ps, ps+ri-is-1, hm); TreeNode rightchild = buildTreePostIn(inorder,ri+1, ie, postorder, ps+ri-is, pe-1, hm); root.left = leftchild; root.right = rightchild; return root; }
similar idea, but no HashMap needed!
(TreeNode end is the boundary of left subtree.)
(TreeNode end is the boundary of left subtree.)
int pInorder; // index of inorder array
int pPostorder; // index of postorder array
private TreeNode buildTree(int[] inorder, int[] postorder, TreeNode end) {
if (pPostorder < 0) {
return null;
}
// create root node
TreeNode n = new TreeNode(postorder[pPostorder--]);
// if right node exist, create right subtree
if (inorder[pInorder] != n.val) {
n.right = buildTree(inorder, postorder, n);
}
pInorder--;
// if left node exist, create left subtree
if ((end == null) || (inorder[pInorder] != end.val)) {
n.left = buildTree(inorder, postorder, end);
}
return n;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
pInorder = inorder.length - 1;
pPostorder = postorder.length - 1;
return buildTree(inorder, postorder, null);
}
X. Iterative Version
https://leetcode.com/discuss/15115/my-comprehension-of-o-n-solution-from-%40hongzhi
https://leetcode.com/discuss/23834/java-iterative-solution-with-explanation
Starting from the last element of the postorder and inorder array, we put elements from postorder array to a stack and each one is the right child of the last one until an element in postorder array is equal to the element on the inorder array. Then, we pop as many as elements we can from the stack and decrease the mark in inorder array until the peek() element is not equal to the mark value or the stack is empty. Then, the new element that we are gonna scan from postorder array is the left child of the last element we have popped out from the stack.
public class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if (inorder == null || inorder.length < 1) return null; int i = inorder.length - 1; int p = i; TreeNode node; TreeNode root = new TreeNode(postorder[postorder.length - 1]); Stack<TreeNode> stack = new Stack<>(); stack.push(root); p--; while (true) { if (inorder[i] == stack.peek().val) { // inorder[i] is on top of stack, pop stack to get its parent to get to left side if (--i < 0) break; node = stack.pop(); if (!stack.isEmpty() && inorder[i] == stack.peek().val) {// continue pop stack to get to left side continue; } node.left = new TreeNode(postorder[p]); stack.push(node.left); } else { // inorder[i] is not on top of stack, postorder[p] must be right child node = new TreeNode(postorder[p]); stack.peek().right = node; stack.push(node); } p--; } return root; } }
https://leetcode.com/discuss/4761/why-my-code-memory-limit-exceeded%EF%BC%9F
This solution will construct many vectors which may consume lots of memory on the stack.
You can do the same job using a helper function that manipulates iterators to avoid the extra space overhead.