-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstruct_BinaryTree.cpp
More file actions
61 lines (45 loc) · 875 Bytes
/
Construct_BinaryTree.cpp
File metadata and controls
61 lines (45 loc) · 875 Bytes
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <climits>
using namespace std;
class Node{
public:
int data;
Node *left,*right;
Node(int val){
data=val;
left=right=NULL;
}
};
Node *ConstructBST(int preorder[],int *idx,int key,int min,int max,int n){
if(*idx>=n){
return NULL;
}
Node *root=NULL;
if(key>min && key<max){
root=new Node(key);
*idx=*idx+1;
if(*idx<n){
root->left=ConstructBST(preorder,idx,preorder[*idx],min,key,n);
}
if(*idx<n){
root->right=ConstructBST(preorder,idx,preorder[*idx],key,max,n);
}
}
return root;
}
void printPreorder(Node *root){
if(root==NULL){
return;
}
cout<<root->data<<" ";
printPreorder(root->left);
printPreorder(root->right);
}
int main(){
int preorder[]={10,2,1,13,11};
int n=5;
int idx=0;
Node *root=ConstructBST(preorder,&idx,preorder[0],INT_MIN,INT_MAX,n);
printPreorder(root);
return 0;
}