Leetcode 889. 根据前序和后序遍历构造二叉树 construct-binary-tree-from-preorder-and-postorder-traversal

* 返回与给定的前序和后序遍历匹配的任何二叉树。
*
* pre 和 post 遍历中的值是不同的正整数。
 
* 示例:
*
* 输入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
* 输出:[1,2,3,4,5,6,7]
 
* 提示:
*
*
* 1 <= pre.length == post.length <= 30
* pre[] 和 post[] 都是 1, 2, ..., pre.length 的排列
* 每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。
 
思路:labuladong
根据前序和后序无法得到唯一解,因为无法确定左右子树的位置。因此可以简单粗暴的选择左边第一个作为左子结点,然后在后序中查找这个结点来确定左子树的长度。这里需要注意,因为查找的是左子树的根节点,所以左子树长度为index-poststart+1

 

 

复制代码
class Solution {
public:
    TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {
        TreeNode* root=build(preorder,0,preorder.size()-1,
                            postorder,0,postorder.size()-1);
        return root;
    }
    TreeNode* build(vector<int>& preorder, int prestart, int preend,
                     vector<int>& postorder, int poststart, int postend){
        if(prestart>preend){
            return nullptr;
        }
        if(prestart==preend){
            return new TreeNode(preorder[prestart]);
        }
        int val=preorder[prestart];
        int leftval=preorder[prestart+1];
        int index=0;
        for(int i=poststart;i<postend;++i){
            if(postorder[i]==leftval){
                index=i;
                break;
            }
        }
        TreeNode* root=new TreeNode(val);
        int n=index-poststart+1;
        root->left=build(preorder,prestart+1,prestart+n,postorder,poststart,index);
        root->right=build(preorder,prestart+n+1,preend,postorder,index+1,postend-1);
        return root;
    }
};
复制代码

 

posted @   鸭子船长  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2017-02-08 【Android Studio】为Android Studio设置HTTP代理
2017-02-08 android-problem——remount of /system failed: Read-only file system
2017-02-08 Android——坐标系及转化
点击右上角即可分享
微信分享提示