-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstructbstfrominorder.cpp
More file actions
74 lines (63 loc) · 1.13 KB
/
constructbstfrominorder.cpp
File metadata and controls
74 lines (63 loc) · 1.13 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node*left,*right;
};
Node*getNode(int data)
{
Node*newnode = new Node;
newnode->data = data;
newnode->left = NULL;
newnode->right = NULL;
}
Node*LevelOrder(Node*root,int data)
{
if(root==NULL)
{
root = getNode(data);
return root;
}
if(data<=root->data)
{
root->left = LevelOrder(root->left,data);
}
else
{
root->right = LevelOrder(root->right,data);
}
return root;
}
Node*constructBst(int arr[],int n)
{
if(n==0)
{
return NULL;
}
Node*root = NULL;
for(int i=0;i<n;i++)
{
root = LevelOrder(root,arr[i]);
}
return root;
}
void inorderTraversal(Node*root)
{
if(!root)
{
return;
}
inorderTraversal(root->left);
cout<<root->data<<" ";
inorderTraversal(root->right);
}
int main()
{
int arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10};
int n = sizeof(arr) / sizeof(arr[0]);
Node *root = constructBst(arr, n);
cout << "Inorder Traversal: ";
inorderTraversal(root);
return 0;
}