LeetCode #889. Construct Binary Tree from Preorder and Postorder Traversal

本文介绍了一种算法,该算法可以根据给定的预序和后序遍历序列重建二叉树。通过分析序列特征,算法能够确定每个节点的位置,从而构建出与原始序列匹配的二叉树结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

Return any binary tree that matches the given preorder and postorder traversals.

Values in the traversals pre and post are distinct positive integers.

Example 1:

Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]

Note:

  • 1 <= pre.length == post.length <= 30
  • pre[] and post[] are both permutations of 1, 2, ..., pre.length.
  • It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.
class Solution {
public:
    TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
        for(int i=0;i<post.size();i++) index[post[i]]=i;
        return construct_tree(pre,post,0,pre.size()-1,0,post.size()-1);
    }
    
    TreeNode* construct_tree(vector<int>& pre, vector<int>& post, int a, int b, int c, int d)
    {
        if(a>b) return NULL;
        if(a==b) return new TreeNode(pre[a]);
        int root_val=pre[a];
        int left_val=pre[a+1];
        int left_length=index[left_val]-c+1; // 左子树的节点数
        TreeNode* root=new TreeNode(root_val);
        root->left=construct_tree(pre,post,a+1,a+left_length,c,c+left_length-1);
        root->right=construct_tree(pre,post,a+left_length+1,b,c+left_length,d-1);
        return root;
    }
    
private:
    unordered_map<int,int> index; // 存储后序遍历值和下标之间的关系
};

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值