106. Construct Binary Tree from Inorder and Postorder Traversal | Java最短代码实现

原题链接: 106. Construct Binary Tree from Inorder and Postorder Traversal 相似博文: 105. Construct Binary Tree from Preorder and Inorder Traversal | Java最短代码实现

【思路】

本题考查根据中序遍历和后序遍历构造二叉树。其基本思路,就是找到后序遍历的最后一个数的值,然后在中序遍历中找到这个值。以这个值作为根,将中序遍历划分为左、右子树序列——前边的序列为左子树的中序遍历,后边的序列为右子树的中序遍历。照此递归左右子树:

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return createTree(inorder, 0, postorder.length - 1, postorder,
                postorder.length - 1);
    }
    private TreeNode createTree(int[] inorder, int inBeg, int inEnd,
            int[] postorder, int postIndex) {
        if (postIndex < 0) return null;
        int mid = 0;
        for (int i = inBeg; i <= inEnd; i++)
            if (inorder[i] == postorder[postIndex]) {
                mid = i;
                break;
            }
        TreeNode root = new TreeNode(inorder[mid]);
        if (mid - inBeg > 0)  //判断左子树节点数是否大于0。下面的postIndex - (inEnd - mid) - 1代表左子树的根节点在postorder中的下标
            root.left = createTree(inorder, inBeg, mid - 1, postorder, postIndex - (inEnd - mid) - 1);
        if (inEnd - mid > 0)  //判断右子树节点数是否大于0。下面的<span style="font-family: Arial, Helvetica, sans-serif;">postIndex - 1代表右子树的根节点在postorder中的下标</span>
            root.right = createTree(inorder, mid + 1, inEnd, postorder, postIndex - 1);
        return root;
    }
202 / 202  test cases passed. Runtime: 21 ms  Your runtime beats 17.86% of javasubmissions.

欢迎优化!

你可能感兴趣的:(106. Construct Binary Tree from Inorder and Postorder Traversal | Java最短代码实现)