-
Notifications
You must be signed in to change notification settings - Fork 1
/
NextRightNode.cpp
129 lines (105 loc) · 2.73 KB
/
NextRightNode.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// TechieDelight https://www.techiedelight.com/find-next-node-in-same-level-binary-tree/
#include <vector>
#include <iostream>
#include <list>
#include <climits>
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);
}
// Construct a balanced tree https://www.techiedelight.com/construct-balanced-bst-given-keys/
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 findNextRight(int key)
{
if (root == nullptr || key == INT_MIN) {
return INT_MIN;
}
std::list<Node*> queue;
queue.push_back(root);
Node* current = nullptr;
while (!queue.empty()) {
int size = queue.size();
while (size--) {
current = queue.front();
queue.pop_front();
if (current->key == key) {
if (size == 0) {
return INT_MIN;
}
return queue.front()->key;
}
if (current->left != nullptr) {
queue.push_back(current->left);
}
if (current->right != nullptr) {
queue.push_back(current->right);
}
}
}
return INT_MIN;
}
};
void test(Tree& tree, int key)
{
std::cout << "Next right of " << key;
int right = tree.findNextRight(key);
if (right == INT_MIN) {
std::cout << " does not exists\n";
} else {
std::cout << " is " << right << "\n";
}
}
int main()
{
std::vector<int> keys { 15, 10, 20, 8, 12, 16, 25 };
Tree tree(keys);
tree.inorder();
test(tree, 10);
test(tree, 25);
}