public TreeNode buildTree(int[] in, int[] post) {
if(in == null  post == null  in.length == 0  post.length == 0  in.length != post.length) return null;
Stack<TreeNode> s = new Stack<TreeNode>();
int i = in.length1;
int j = post.length1;
TreeNode root = new TreeNode(post[j]);
s.push(root);
TreeNode current = root, temp = null, right = null, left = null;
while(i >= 0) {
if(!s.isEmpty() && s.peek().val == in[i]) {
temp = s.pop();
i;
} else if(temp != null) {
left = new TreeNode(post[j]);
s.push(left);
temp.left = left;
current = left;
temp = null;
} else {
right = new TreeNode(post[j]);
s.push(right);
current.right = right;
current = current.right;
}
}
return root;
}
Iterative method, java


For those who want to take a look at iterative method, you can read the paper
Nonrecursive algorithms for constructing binary tree from its traversals