重建二叉树
- 根据先序遍历和中序遍历重建二叉树
- 问题1:vector分片
- 问题2:相似语句复制粘贴容易出问题而且不易察觉(特别是仅有下标不同的情况)
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
37
38
39
40
41
42
43
44
45struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in)
{
if(pre.empty() || in.empty()) return NULL;
TreeNode* root = new TreeNode(pre[0]);
int i;
for(i=0; i<pre.size();i++)
if(pre[0] == in[i]) break;
vector<int> pre1(pre.begin()+1, pre.begin()+i+1);
vector<int> pre2(pre.begin()+i+1, pre.end());
vector<int> in1(in.begin(), in.begin()+i);
vector<int> in2(in.begin()+i+1, in.end());
//vector<int>::iterator it;
//for(it = pre1.begin();it!=pre1.end();it++)
// cout << *it << "\t";
//cout << endl;
//for(it = pre2.begin();it!=pre2.end();it++)
// cout << *it << "\t";
//cout << endl;
//for(it = in1.begin();it!=in1.end();it++)
// cout << *it << "\t";
//cout << endl;
//for(it = in2.begin();it!=in2.end();it++)
// cout << *it << "\t";
//cout << endl;
root->left = reConstructBinaryTree(pre1,in1);
root->right = reConstructBinaryTree(pre2,in2);
return root;
}