leetcode 106. 从中序与后序遍历序列构造二叉树

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

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

例如,给出

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

3
/ \
9 20
/ \
15 7

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (postorder == null || postorder.length == 0) {
            return null;
        }
        int length = postorder.length - 1;
        TreeNode node = new TreeNode(postorder[ length]);
        find (postorder, inorder, node, 0, length, 0, length);
        return node;
    }

    private void find (int[] postorder, int[] inorder, TreeNode node, int st, int end, int st2, int end2) {
        if (st > end) {
            return;
        }
        int value = postorder[end];
        int split = st2;
        for (int j = st2 ; j <= end2; j++) {
            if (inorder[j] == value) {
                split = j;
                break;
            }
        }
        int leftLength = split - st2;
        if (leftLength != 0) {
            TreeNode l = new TreeNode(postorder[st + leftLength - 1]);
            node.left = l;
            find (postorder, inorder, l, st, st + leftLength - 1, st2, split - 1);
        }
        if (split != end2) {
            TreeNode r = new TreeNode(postorder[end - 1]);
            node.right = r;
            find (postorder, inorder, r, st + leftLength, end - 1, split + 1, end2);
        }
    }

posted @ 2021-04-28 14:47  旺仔古李  阅读(48)  评论(0编辑  收藏  举报