-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild_bst_from_preorder.cpp
59 lines (44 loc) · 1.15 KB
/
build_bst_from_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
48
49
50
51
52
53
54
55
56
57
58
59
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node(int val) {
data = val;
left = NULL;
right = NULL;
}
};
Node* BSTfromPreorder(int preorder[], int* preorderIdx, int key, int min, int max, int n) {
if(*preorderIdx >= n) {
return NULL;
}
Node* root = NULL;
if(key>min && key<max) {
root = new Node(key);
++*preorderIdx;
if(*preorderIdx < n) {
root->left = BSTfromPreorder(preorder, preorderIdx, preorder[*preorderIdx], min, key, n);
}
if(*preorderIdx < n) {
root->right = BSTfromPreorder(preorder, preorderIdx, preorder[*preorderIdx], 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 preorderIdx = 0;
Node* root = BSTfromPreorder(preorder, &preorderIdx, preorder[0], INT_MIN, INT_MAX, n);
printPreorder(root);
return 0;
}