一:题目
二:上码
class Solution {
public TreeNode getTree(int leftIn,int rightIn,int leftPost,int rightPost,int[] in,int[] post) {
if (leftIn > rightIn) return null;
int rootIn = leftIn;
while (rootIn <= rightIn && in[rootIn] != post[rightPost]) rootIn++;
int leftNums = rootIn - leftIn;
TreeNode root = new TreeNode(post[rightPost]);
root.left = getTree(leftIn,rootIn-1,leftPost,leftPost+leftNums-1,in,post);
root.right = getTree(rootIn+1,rightIn,leftPost+leftNums,rightPost - 1,in,post);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
return getTree(0,inorder.length-1,0,postorder.length-1,inorder,postorder);
}
}
|