construct-binary-tree-from-preorder-and-inorder-traversal——前序和中序求二叉树
2024-09-08 01:11:41
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
if(preorder.size()!=inorder.size()) return NULL;
return build(preorder,inorder,,preorder.size()-,,inorder.size()-);
} TreeNode *build(vector<int> &preorder, vector<int> &inorder,int s1,int e1,int s2,int e2){
if(s1>e1||s2>e2) return NULL;
if(s1==e1) return new TreeNode(preorder[s1]);
TreeNode *res=new TreeNode(preorder[s1]);
int tmp=preorder[s1];
int index=;
while((s2+index)<=e2){
if(inorder[s2+index]==tmp)
break;
index++;
}
res->left=build(preorder,inorder,s1+,s1+index,s2,s2+index-);
res->right=build(preorder,inorder,s1+index+,e1,s2+index+,e2);
return res;
}
};
最新文章
- 使用Ring Buffer构建高性能的文件写入程序
- Event Store 2.0发布,带来了安全支持和测试版Projections库
- 天气api
- Mvc4页面缓存设置Cookie导致缓存失效
- mysql学习笔记 第九天
- Html页面插入flash代码
- ASP.NET MVC- 解决HTML转码
- iOS多线程编程Part 2/3 - NSOperation
- Socket理解
- Asynchronous
- JavaScript Window.document对象
- Mybatis框架可视化(1)
- Python进行Android开发步骤
- MySQL数据库如何去掉数据库中重复记录
- 【洛谷 P5110】 块速递推(矩阵加速,分块打表)
- RTL2832U+R820T电视棒windows下安装sdr# 以及搭建ADS-B使用VirtualRadar看飞机的教程
- .NET--百度百科
- java 调用cmd命令
- Hibernate查询语言(HQL)
- JAVA基础之Properties类、序列化流及打印流、commons-IO