Construct Binary Tree from Inorder and Postorder Traversal

https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/

Given inorder and postorder traversal of a tree, construct the binary tree.

Thoughts

和上题思路一致,只是这次root是先从postorder的末尾找。

Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private TreeNode helper(int[] inorder, int instart, int inend, int[] postorder, int pstart, int pend) {
        if (instart > inend || pstart > pend) {
            return null;
        }
        int nodeVal = postorder[pend];
        int inpos = -1;
        // 0, 6 - 0
        for (int i = 0; i <= inend - instart; i++) {
            if (inorder[instart + i] == nodeVal) {
                inpos = i;
            }
        }
        TreeNode node = new TreeNode(inorder[instart + inpos]);
        node.left = helper(inorder, instart, instart + inpos - 1, postorder, pstart, pstart + inpos - 1);
        node.right = helper(inorder, instart + inpos + 1, inend, postorder, pstart + inpos, pend - 1);
        return node;
    }

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

Analysis

Errors:

  1. inorder[instart + i] == nodeVal忘了写instart

    做题耗时: 15min

时间复杂度O(n^2).

Ver.2

和preorder-inorder同理, 只不过要倒过来处理. 从尾部遍历先建右树再建左树. 时间复杂度O(N).

Last updated

Was this helpful?