后序遍历的最后一个值是树的根节点,在中序遍历中找到该节点,根据中序遍历的特点(左子树-根-右子树),所以在中序遍历中,把根节点左边的值都放进左子树递归,把根节点右边的值都放进右子树递归。
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
int len1=inorder.length-1;
int len2=postorder.length-1;
TreeNode root=reBuildTree(inorder,0,len1,postorder,0,len2);
return root;
}
public TreeNode reBuildTree(int[] inorder,int start1,int end1,int[] postorder,int start2,int end2){
if(start1>end1||start2>end2)
return null;
TreeNode root=new TreeNode(postorder[end2]);
for(int i=start1;i<=end1;i++){
if(inorder[i]==postorder[end2]){
root.left=reBuildTree(inorder,start1,i-1,postorder,start2,start2+i-start1-1);
root.right=reBuildTree(inorder,i+1,end1,postorder,start2+i-start1,end2-1);
break;
}
}
return root;
}
}