forked from fineanmol/Hacktoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tree.cpp
74 lines (65 loc) · 2.04 KB
/
tree.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
#include <bits/stdc++.h>
void markParents(BinaryTreeNode<int> *root, unordered_map<BinaryTreeNode<int> *, BinaryTreeNode<int> *> &parent_track, BinaryTreeNode<int> *target)
{
queue<BinaryTreeNode<int> *> queue;
queue.push(root);
while (!queue.empty())
{
BinaryTreeNode<int> *current = queue.front();
queue.pop();
if (current->left)
{
parent_track[current->left] = current;
queue.push(current->left);
}
if (current->right)
{
parent_track[current->right] = current;
queue.push(current->right);
}
}
}
vector<BinaryTreeNode<int> *> printNodesAtDistanceK(BinaryTreeNode<int> *root, BinaryTreeNode<int> *target, int k)
{
unordered_map<BinaryTreeNode<int> *, BinaryTreeNode<int> *> parent_track;
markParents(root, parent_track, target);
unordered_map<BinaryTreeNode<int> *, bool> visited;
queue<BinaryTreeNode<int> *> queue;
queue.push(target);
visited[target] = true;
int curr_level = 0;
while (!queue.empty())
{
int size = queue.size();
if (curr_level++ == k)
break;
for (int i = 0; i < size; i++)
{
BinaryTreeNode<int> *current = queue.front();
queue.pop();
if (current->left && !visited[current->left])
{
queue.push(current->left);
visited[current->left] = true;
}
if (current->right && !visited[current->right])
{
queue.push(current->right);
visited[current->right] = true;
}
if (parent_track[current] && !visited[parent_track[current]])
{
queue.push(parent_track[current]);
visited[parent_track[current]] = true;
}
}
}
vector<BinaryTreeNode<int> *> result;
while (!queue.empty())
{
BinaryTreeNode<int> *current = queue.front();
queue.pop();
result.push_back(current);
}
return result;
}