-
Notifications
You must be signed in to change notification settings - Fork 0
/
130. ConstructaBTfromInorderPreorder.cpp
48 lines (36 loc) · 1.32 KB
/
130. ConstructaBTfromInorderPreorder.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
#include <bits/stdc++.h>
/************************************************************
Following is the TreeNode class structure
template <typename T>
class TreeNode {
public:
T data;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T data) {
this->data = data;
left = NULL;
right = NULL;
}
};
************************************************************/
TreeNode<int> * buildTree(vector<int> &preorder, int preStart, int preEnd, vector<int> &inorder,
int inStart, int inEnd, map<int,int> &mp){
if(preStart > preEnd || inStart > inEnd)return NULL;
TreeNode<int> * root = new TreeNode<int> (preorder[preStart]);
int inRoot = mp[root->data];
int numsLeft = inRoot - inStart;
root->left = buildTree(preorder, preStart+1, preStart+numsLeft, inorder, inStart, inRoot-1, mp);
root->right = buildTree(preorder, preStart+numsLeft+1, preEnd, inorder, inRoot+1, inEnd, mp);
return root;
}
TreeNode<int> *buildBinaryTree(vector<int> &inorder, vector<int> &preorder)
{
map<int, int> mp;
for(int i=0;i<inorder.size();i++){
mp[inorder[i]] = i;
}
TreeNode<int> * root = buildTree(preorder, 0, preorder.size()-1,
inorder, 0, inorder.size()-1, mp);
return root;
}