Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

题意:给出一个二叉树的中序和后序遍历结果,并且这个二叉树中没有重复值,复原这个二叉树。

思路:这道题和105题相比,只是条件从前序换成了后序,但是后序数组的最后一个值仍然是根节点,因此依旧可以用105题的解法解决。

public TreeNode buildTree(int[] inorder, int[] postorder) {
    if (inorder == null || postorder == null || inorder.length != postorder.length) {
        return null;
    }

    return helper(0, inorder.length - 1, 0, postorder.length - 1, inorder, postorder);
}

public TreeNode helper(int inStart, int inEnd, int postStart, int postEnd, int[] inorder, int[] postorder) {
    if (inStart > inEnd || postStart > postEnd) {
        return null;
    }

    //find parent
    TreeNode parent = new TreeNode(postorder[postEnd]);

    //find left right in inorder
    int inIndex = inStart;
    for (int i = inStart; i <= inEnd; i++) {
        if (inorder[i] == postorder[postEnd]) {
            inIndex = i;
            break;
        }
    }

    parent.left = helper(inStart, inIndex - 1, postStart, postStart + inIndex - inStart - 1, inorder, postorder);
    parent.right = helper(inIndex + 1, inEnd, postStart + inIndex - inStart, postEnd - 1, inorder, postorder);

    return parent;
}

你可能感兴趣的:(Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal)