-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortedarraytobst.cpp
More file actions
63 lines (50 loc) · 1 KB
/
sortedarraytobst.cpp
File metadata and controls
63 lines (50 loc) · 1 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
#include<bits/stdc++.h>
using namespace std;
class Tnode
{
public:
int data;
Tnode*left;
Tnode*right;
};
Tnode* newNode(int data)
{
Tnode*node = new Tnode();
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
Tnode*sortedArray(int arr[],int start,int end)
{
if(start>end)
{
return NULL;
}
int mid = (start+end)/2;
TNode*root = newNode(arr[mid]);
root->left = sortedArray(arr,start,mid-1);
root->right = sortedArray(arr,mid+1,end);
return root;
}
//A UTILITY FUNCTION TO PRINT PREORDER TRAVERSAL OF BST
void preOrder(Tnode*node)
{
if(node==NULL)
{
return;
}
cout<<node->data<<" ";
preOrder(node->left);
preOrder(node->right);
}
int main()
{
int arr[] = {1,2,3,4,5,6,7};
int n = sizeof(arr)/sizeof(arr[0]);
//CONVERT LIST TO BST
Tnode*root = sortedArray(arr,0,n-1);
cout<<"PreOrder Traversal to constructed BST \n";
preOrder(root);
return 0;
}