forked from gh877916059/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path073. 前序遍历和中序遍历树构造二叉树.cpp
36 lines (36 loc) · 940 Bytes
/
073. 前序遍历和中序遍历树构造二叉树.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution
{
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
{
TreeNode* fan_hui=NULL;
if(preorder.size()==0)
return fan_hui;
int gen=preorder[0];
int i=0;
for(;i<(int)inorder.size();++i)
{
if(inorder[i]==gen)
break;
}
fan_hui=new TreeNode(gen);
vector<int> pre;
vector<int> ino;
int pre_index=1;
for(int j=0;j<i;++j,++pre_index)
{
ino.push_back(inorder[j]);
pre.push_back(preorder[pre_index]);
}
fan_hui->left=buildTree(pre,ino);
pre.clear();
ino.clear();
for(int j=i+1;j<(int)inorder.size();++j,++pre_index)
{
ino.push_back(inorder[j]);
pre.push_back(preorder[pre_index]);
}
fan_hui->right=buildTree(pre,ino);
return fan_hui;
}
};