forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sortedArrayToBST.cpp
50 lines (44 loc) · 1.05 KB
/
sortedArrayToBST.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
/**
* Given a sorted array, convert it balaned binary search tree.
*/
#include<iostream>
#include<vector>
struct Node {
int data;
Node * left;
Node * right;
Node( int d ) : data{ d }, left{ nullptr }, right{ nullptr } { }
};
Node * sortedArrayToBST( std::vector<int> & arr, int start, int end ) {
if ( start > end ) {
return nullptr;
}
int mid = ( start + end )/2;
Node * node = new Node(arr[mid]);
node->left = sortedArrayToBST( arr, start, mid - 1 );
node->right = sortedArrayToBST( arr, mid + 1, end );
return node;
}
void printArray( std::vector<int> & arr ) {
for ( auto i : arr ) {
std::cout << i << " ";
}
std::cout << std::endl;
}
void printTreeInOrder( Node * root ) {
if( root ) {
printTreeInOrder( root->left );
std::cout << root->data << " ";
printTreeInOrder( root->right );
}
}
int main() {
std::vector<int> arr{ 1, 2, 3, 4, 5, 6, 7, 8 };
std::cout << "Arr :";
printArray(arr);
Node * root = sortedArrayToBST(arr, 0, arr.size() - 1);
std::cout << "Tree :";
printTreeInOrder(root);
std::cout << std::endl;
return 0;
}