-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsortedArrayToBinarySearchTree.cpp
58 lines (45 loc) · 1.15 KB
/
sortedArrayToBinarySearchTree.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
#include<iostream>
using namespace std;
//tree node
class treeNode {
public:
int val;
treeNode *leftChild;
treeNode *rightChild;
treeNode(int value) {
val = value;
leftChild = NULL;
rightChild = NULL;
}
};
//function protoTypes
treeNode* sortedArrayToBinrySearchTree(int a[], int left, int right);
void inOrderTraversal(treeNode * treeNode);
int main() {
//sorted array
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
//BST
treeNode * T2 = sortedArrayToBinrySearchTree(arr, 0, 10);
//print In Order of tree :: will be same as given array
inOrderTraversal(T2);
return 0;
}
//function to construct sorted array to BST
treeNode* sortedArrayToBinrySearchTree(int a[], int left, int right) {
int mid;
if (left > right)
return NULL;
mid = (left + right) / 2;
treeNode *temp = new treeNode(a[mid]);
temp->leftChild = sortedArrayToBinrySearchTree(a, left, mid - 1);
temp->rightChild = sortedArrayToBinrySearchTree(a, mid + 1, right);
return temp;
}
//function to print BST in InOrder
void inOrderTraversal(treeNode * Elem) {
if (Elem) {
inOrderTraversal(Elem->leftChild);
cout << Elem->val << endl;
inOrderTraversal(Elem->rightChild);
}
}