-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConstructBalancedTree.cpp
76 lines (61 loc) · 1.42 KB
/
ConstructBalancedTree.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Techie Delight https://www.techiedelight.com/construct-balanced-bst-given-keys/
#include <vector>
#include <iostream>
class Tree
{
private:
class Node
{
public:
int key;
Node* left;
Node* right;
Node(int k) : key(k), left(nullptr), right(nullptr) { }
};
Node* root;
void print(std::vector<Node*>& path)
{
for (auto node : path) {
std::cout << node->key << " ";
}
std::cout << "\n";
}
void preorder(Node* node, std::vector<Node*>& path)
{
if (node == nullptr) {
return;
}
path.push_back(node);
preorder(node->left, path);
preorder(node->right, path);
}
Node* construct(std::vector<int>& keys, int left, int right)
{
if (left > right) {
return nullptr;
}
int mid = left + (right - left) / 2;
Node* node = new Node(keys[mid]);
node->left = construct(keys, left, mid - 1);
node->right = construct(keys, mid + 1, right);
return node;
}
public:
Tree() : root(nullptr) { }
Tree(std::vector<int> keys)
{
root = construct(keys, 0, keys.size() - 1);
}
void inorder()
{
std::vector<Node*> path;
preorder(root, path);
print(path);
}
};
int main()
{
std::vector<int> keys { 15, 10, 20, 8, 12, 16, 25 };
Tree tree(keys);
tree.inorder();
}