-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstruct_binarytree_from_inroder_preorder.cpp
47 lines (39 loc) · 1.28 KB
/
construct_binarytree_from_inroder_preorder.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
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for a binary tree node.
* 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) {
cout<<preorder.size()<<" "<<inorder.size()<<"\n";
if(preorder.size()==0 || inorder.size()==0)
return NULL;
TreeNode *root = new TreeNode(preorder[0]);
vector<int> inorder_left;
int i;
for(i = 0;i<inorder.size();i++)
{
if(inorder[i]==preorder[0])
break;
inorder_left.push_back(inorder[i]);
}
vector<int> preorder_left;
int j;
for(j=1;j<=i;j++)
preorder_left.push_back(preorder[j]);
root->left = buildTree(preorder_left,inorder_left);
int right_size = inorder.size() - (i+1);
if(right_size > 0)
{
vector<int> inorder_right(inorder.begin() + i + 1,inorder.end());
vector<int> preorder_right(preorder.begin() + i + 1,preorder.end());
root->right = buildTree(preorder_right,inorder_right);
}
return root;
}
};