法1:递归
class Solution {
public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {
return build(preorder, 0, preorder.length - 1, postorder, 0, postorder.length - 1);
}
public TreeNode build(int[] preorder, int preStart, int preEnd, int[] postorder, int postStart, int postEnd) {
if (preStart > preEnd) {
return null;
}
if (preStart == preEnd) {
return new TreeNode(preorder[preStart]);
}
TreeNode root = new TreeNode(preorder[preStart]);
int lastLeftInx = -1;
for (int i = postStart; i <= postEnd; ++i) {
if (postorder[i] == preorder[preStart + 1]) {
lastLeftInx = i;
break;
}
}
int leftSize = lastLeftInx - postStart + 1;
root.left = build(preorder, preStart + 1, preStart + leftSize, postorder, postStart, lastLeftInx);
root.right = build(preorder, preStart + leftSize + 1, preEnd, postorder, lastLeftInx + 1, postEnd - 1);
return root;
}
}