Leetcode 889: Construct Binary Tree from Preorder and Postorder Traversal (二叉树构建好题)

  1. Construct Binary Tree from Preorder and Postorder Traversal
    Medium

Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.

If there exist multiple answers, you can return any of them.

Example 1:

Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
Example 2:

Input: preorder = [1], postorder = [1]
Output: [1]

Constraints:

1 <= preorder.length <= 30
1 <= preorder[i] <= preorder.length
All the values of preorder are unique.
postorder.length == preorder.length
1 <= postorder[i] <= postorder.length
All the values of postorder are unique.
It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree.

解法1:注意构建的二叉树不唯一。如果root只有一个子节点,有可能左子树为空,也有可能右子树为空。这里我们假定这种情况左子树存在,右子树为空。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {
        int n = preorder.size(), n2 = postorder.size();
        if (n == 0 || n != n2) return NULL;
        for (int i = 0; i < n; i++) {
            um[postorder[i]] = i;
        }
        return helper(preorder, 0, n - 1, postorder, 0, n - 1);
    }
private:
    unordered_map<int, int> um; //<value, index in postorder>
    TreeNode *helper(vector<int>& preorder, int start1, int end1, vector<int>& postorder, int start2, int end2) {
        if (start1 > end1) return NULL;
        TreeNode *root = new TreeNode(preorder[start1]);
        if (start1 == end1) return root;
        int leftIndex = um[preorder[start1 + 1]]; //这里是start1!
        int leftSize = leftIndex - start2 + 1; //注意是start2,不是start1!!!
        root->left = helper(preorder, start1 + 1, start1 + leftSize, postorder, start2, leftIndex - 1);
        root->right = helper(preorder, start1 + leftSize + 1, end1, postorder, leftIndex + 1, end2 - 1);
        return root;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值