-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst_preorder.cpp
57 lines (51 loc) · 1.12 KB
/
bst_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
#include<iostream>
#include<climits>
using namespace std;
struct Node
{
int data;
Node *left, *right;
Node(int val)
{
data = val;
left = NULL;
right = NULL;
}
};
Node* constructBST(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 += 1;
if(*preorderIdx < n)
{
root->left = constructBST(preorder, preorderIdx, preorder[*preorderIdx], min, key, n);
}
if(*preorderIdx < n)
{
root->right = constructBST(preorder, preorderIdx, preorder[*preorderIdx], key, max, n);
}
}
return root;
}
void inorder(Node* root)
{
if(root == NULL)
return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
int main()
{
int preorder[] = {7,5,4,6,8,9};
int n = 6;
int preorderIdx = 0;
Node* root = constructBST(preorder, &preorderIdx, preorder[0], INT_MIN, INT_MAX, n);
inorder(root);
return 0;
}