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; } };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.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——坐标系及转化