题目
法1:递归构造
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
public TreeNode build(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) {
if (postStart > postEnd) {
return null;
}
if (postStart == postEnd) {
return new TreeNode(postorder[postEnd]);
}
TreeNode root = new TreeNode(postorder[postEnd]);
int valInx = -1;
for (int i = inStart; i <= inEnd; ++i) {
if (inorder[i] == postorder[postEnd]) {
valInx = i;
break;
}
}
int leftSize = valInx - inStart;
root.left = build(inorder, inStart, valInx - 1, postorder, postStart, postStart + leftSize - 1);
root.right = build(inorder, valInx + 1, inEnd, postorder, postStart + leftSize, postEnd - 1);
return root;
}
}