Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode constructBTree(int[] inorder,int istart,int iend,int[] postorder,int pstart,int pend){
int root=-1;
TreeNode node=new TreeNode(postorder[pend]);
for(int i=istart;i<=iend;i++){
if(postorder[pend]==inorder[i]){
root=i;
break;
}
}
if(root>istart){
int len=root-istart;
node.left=constructBTree(inorder,istart,root-1,postorder,pstart,pstart+len-1);
}
if(root<iend){
int len=iend-root;
node.right=constructBTree(inorder,root+1,iend,postorder,pend-len,pend-1);
}
return node;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
TreeNode root=null;
int len=postorder.length;
if(postorder==null||len==0){
return null;
}
root=constructBTree(inorder,0,len-1,postorder,0,len-1);
return root;
}
}