Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
=================
A scary problem at the very beginning. What we can do is to try an example for both inorder and postorder traversal, and find out the pattern between these two arrays.
in-order: A,B,C,D,E,F,G,H,I
post-order: A, C, E, D, B, H, I, G, F
From which we can found that the right most element in post-order array is the root node, then use this element as the split point, we can split the in-order array into left part and right part. Tree nodes in left part are belong to current root node's left sub-tree, while the nodes in right part are belong to current root node's right sub-tree.
Accordingly, we can use recursive approach to further build current node's left sub-tree and right sub-tree.
Note that the position of split point for in order array (inside the current array) and post order array (always at the end of the current array) are different. Therefore, we need to specify left/right bond of sub-array for in order array and post order array respectively.
/**
* 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) {
return helper(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
}
public TreeNode helper(int[] inorder, int inLeft, int inRight, int[] postorder, int postLeft, int postRight){
if(inLeft>inRight||postLeft>postRight) return null;
TreeNode curr = new TreeNode(postorder[postRight]);
int splitPoint = 0;
for(int i=inLeft; i<=inRight; i++){
if(inorder[i] == curr.val){
splitPoint = i;
break;
}
}
curr.left = helper(inorder, inLeft, splitPoint-1, postorder, postLeft, postLeft+(splitPoint-inLeft-1));
// splitPoint-inLeft-1 is the length of subarray
curr.right = helper(inorder, splitPoint+1, inRight, postorder, postLeft+(splitPoint-inLeft), postRight-1);
return curr;
}
}