思路:
我们知道,中序遍历是:左子树,root,右子树,
而后序遍历是:左子树,右子树,root。
所以,后序遍历的最后一个元素是root,
搜索这个root在inorder中的位置,就可以把inorder的左子树,右子树的范围找出来,
利用这个范围(长度),又可以把postorder中的左子树,右子树找出来。
然后递归,再build 左子树和右子树范围的inorder, postorder.
例如,找到root对应的inorder的位置为rootIdx:
因此可以得到inorder中左子树范围:start~ rootIdx -1
右子树子范围:rootIdx + 1 ~ end
进而得到右子树size = end - rootIdx
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
int n = inorder.length;
return build(inorder, postorder, 0, n-1, 0, n-1);
}
TreeNode build(int[] inorder, int[] postorder, int iS, int iE,
int pS, int pE) {
if(iS > iE || pS > pE) return null;
int rootVal = postorder[pE];
TreeNode root = new TreeNode(rootVal);
int rootIdx = iS;
while(rootIdx <= iE) {
if(inorder[rootIdx] == rootVal) break;
rootIdx ++;
}
//不能用binarySearch,因为不是排序的
//int rootIdx = Arrays.binarySearch(inorder, rootVal);
root.left = build(inorder, postorder, iS, rootIdx-1, pS, pS+rootIdx-1-iS);
root.right = build(inorder, postorder, rootIdx+1, iE, pS+rootIdx-iS, pE-1);
return root;
}
}