Given inorder and postorder traversal of a tree, construct the binary tree.
import java.util.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;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] inorder = {4,2,5,1,6,3,7};
int[] postorder = {4,5,2,6,7,3,1};
TreeNode node = solution.buildTree(inorder, postorder);
System.out.println(node);
}
}
// int pInorder; // index of inorder array
// int pPostorder; // index of postorder array
//
// public TreeNode buildTree(int[] inorder, int[] postorder) {
// pInorder = inorder.length - 1;
// pPostorder = postorder.length - 1;
//
// return buildTree(inorder, postorder, null);
// }
//
// 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;
// }
https://leetcode.com/discuss/23834/java-iterative-solution-with-explanation
the key point is to scanning the postorder array from end to beginning and also use inorder array from end to beginning as a mark because the logic is more clear in this way. The core idea is: 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.