思路:
本题的思路与LeetCode105题:从前序与中序遍历序列构造二叉树的思路非常类似。只不过这里要根据后序遍历序列遍历当前节点而已。
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return helpBuild(inorder,postorder,postorder.length - 1,0,inorder.length);
}
public TreeNode helpBuild(int[] in, int[] post, int postIndex, int inFrom, int inTo) {
if(inFrom >= inTo){
return null;
}
TreeNode root = new TreeNode(post[postIndex]);
for(int i=inFrom;i<inTo;i++){
if(in[i] == post[postIndex]){
root.right = helpBuild(in,post,postIndex - 1,i + 1,inTo);
root.left = helpBuild(in,post,postIndex - (inTo - i),inFrom,i);
break;
}
}
return root;
}
}