欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 力扣-105.从前序与中序遍历序列构造二叉树

力扣-105.从前序与中序遍历序列构造二叉树

2025/5/18 3:35:10 来源:https://blog.csdn.net/weixin_46878941/article/details/147956959  浏览:    关键词:力扣-105.从前序与中序遍历序列构造二叉树

题目描述

给定两个整数数组 preorderinorder ,其中 preorder 是二叉树的先序遍历inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

class Solution {
public:TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {if(preorder.size()==0)return NULL;TreeNode* root = new TreeNode(preorder[0]);if(preorder.size()==1)return root;int index = 0;for (int i = 0; i < inorder.size(); ++i) {if(inorder[i]==preorder[0])index = i;}vector<int> leftIn(inorder.begin(), inorder.begin()+index);vector<int> rightIn(inorder.begin()+index+1, inorder.end());vector<int> leftPre(preorder.begin()+1,preorder.begin()+1+index);vector<int> rightPre(preorder.begin()+1+index,preorder.end());root->left = buildTree(leftPre,leftIn);root->right = buildTree(rightPre,rightIn);return root;}
};

小结:递归的思路也是非常清晰,C++vector切割数组真的很方便,大概思路就是先用先序集合确定根结点,再找到在中序的位置,之后切割、递归。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词