Skip to content

Commit 42db72c

Browse files
committed
Add construct balanced binary tree
1 parent 3d23afe commit 42db72c

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ Princeton Algorithms [Part 1](https://www.coursera.org/learn/algorithms-part1/)
111111
## Binary Tree
112112
* Binary tree
113113
* Recursive Preorder, inorder, postorder, height, diameter [C++](problems/binary-tree/BasicTree.cpp)
114+
* Construct balanced binary tree [C++](problems/binary-tree/ConstructBalancedTree.cpp)
114115
* Find longest increasing path in binary tree [C++](problems/binary-tree/LongestPathInBinaryTree.cpp)
115116
* Find longest increasing path in n-ary tree [C++](problems/binary-tree/LongestPathInNaryTree.cpp)
116117

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Techie Delight https://www.techiedelight.com/construct-balanced-bst-given-keys/
2+
3+
#include <vector>
4+
#include <iostream>
5+
6+
class Tree
7+
{
8+
private:
9+
class Node
10+
{
11+
public:
12+
int key;
13+
Node* left;
14+
Node* right;
15+
16+
Node(int k) : key(k), left(nullptr), right(nullptr) { }
17+
};
18+
19+
Node* root;
20+
21+
void print(std::vector<Node*>& path)
22+
{
23+
for (auto node : path) {
24+
std::cout << node->key << " ";
25+
}
26+
std::cout << "\n";
27+
}
28+
29+
void preorder(Node* node, std::vector<Node*>& path)
30+
{
31+
if (node == nullptr) {
32+
return;
33+
}
34+
path.push_back(node);
35+
preorder(node->left, path);
36+
preorder(node->right, path);
37+
}
38+
39+
Node* construct(std::vector<int>& keys, int left, int right)
40+
{
41+
if (left > right) {
42+
return nullptr;
43+
}
44+
45+
int mid = left + (right - left) / 2;
46+
Node* node = new Node(keys[mid]);
47+
48+
node->left = construct(keys, left, mid - 1);
49+
node->right = construct(keys, mid + 1, right);
50+
51+
return node;
52+
}
53+
54+
public:
55+
Tree() : root(nullptr) { }
56+
57+
Tree(std::vector<int> keys)
58+
{
59+
root = construct(keys, 0, keys.size() - 1);
60+
}
61+
62+
void inorder()
63+
{
64+
std::vector<Node*> path;
65+
preorder(root, path);
66+
print(path);
67+
}
68+
69+
};
70+
71+
int main()
72+
{
73+
std::vector<int> keys { 15, 10, 20, 8, 12, 16, 25 };
74+
Tree tree(keys);
75+
tree.inorder();
76+
}

0 commit comments

Comments
 (0)