题目描述

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

示例:

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

思路

1.思路与105. 从前序与中序遍历序列构造二叉树基本一致。
2.在二叉树后序遍历的数组中,找到根的位置。
3.然后中序遍历的数组中根据根的值,找到左子树和右子树的分割点,递归下去即可。

Java代码实现

   public TreeNode buildTree(int[] inorder, int[] postorder) {
         return buildTree(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
    }

    public TreeNode buildTree(int[] inorder,int inStart,int inEnd, int[] postorder,int postStart,int postEnd) {
        if(inStart > inEnd || postStart > postEnd)
            return null;
        //根的值
        int rootVal = postorder[postEnd];
        int i;
        for (i = 0; i <= inEnd - inStart; i++) {
            if(inorder[inStart+i] == rootVal)
                break;
        }
        TreeNode root = new TreeNode(rootVal);
        root.left = buildTree(inorder,inStart,inStart+i-1,postorder,postStart,postStart+i-1);
        root.right = buildTree(inorder,inStart+i+1,inEnd,postorder,postStart+i,postEnd-1);
        return root;
    }