Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Example:
inorder: DBEFAGC
postorder: DFEBGCA
Root start with the last element of postorder array, A. In inorder array, all elements going before A are left child, and all elements following after A are right child. And the next right root start with C, left root start with B, both of whose position can be inferred from position of A in inorder and postorder array.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || inorder.length == 0 || postorder == null || postorder.length == 0) {
return null;
}
return helperTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
private TreeNode helperTree(int[] inorder, int instart, int inend, int[] postorder, int poststart, int postend) {
if (instart > inend) {
return null;
}
TreeNode root = new TreeNode(postorder[postend]);
int pos = findPos(inorder, instart, inend, postorder[postend]);
root.right = helperTree(inorder, pos + 1, inend, postorder, poststart + pos - instart, postend - 1);
root.left = helperTree(inorder, instart, pos - 1, postorder, poststart, poststart + pos - instart - 1);
return root;
}
private int findPos(int[] array, int start, int end, int key) {
for (int i = start; i <= end; i++) {
if (array[i] == key) {
return i;
}
}
return -1;
}
}