-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path10 October Nodes at given distance in binary tree
More file actions
87 lines (66 loc) · 1.88 KB
/
10 October Nodes at given distance in binary tree
File metadata and controls
87 lines (66 loc) · 1.88 KB
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
class Solution {
private:
void addNodesBelowAtK(Node* root, int k, vector<int>& ans)
{
if (root == nullptr || k < 0)
return;
if (k == 0)
{
ans.push_back(root->data);
return;
}
addNodesBelowAtK(root->left, k - 1, ans);
addNodesBelowAtK(root->right, k - 1, ans);
}
Node* findTargetNode(Node* root, int target)
{
if (root == nullptr)
return nullptr;
if (root->data == target)
return root;
Node* l = findTargetNode(root->left, target);
Node* r = findTargetNode(root->right, target);
if (l != nullptr)
return l;
if (r != nullptr)
return r;
return nullptr;
}
int addNodesOnAncestorAtK(Node* root, Node* target, int k, vector<int>& ans)
{
if (root == nullptr)
return -1;
if (root == target) {
return 0;
}
int l = addNodesOnAncestorAtK(root->left, target, k, ans);
if (l >= 0)
{
if (l + 1 == k)
ans.push_back(root->data);
else
addNodesBelowAtK(root->right, k - 2 - l, ans);
return l + 1;
}
int r = addNodesOnAncestorAtK(root->right, target, k, ans);
if (r >= 0)
{
if (r + 1 == k)
ans.push_back(root->data);
else
addNodesBelowAtK(root->left, k - 2 - r, ans);
return r + 1;
}
return -1;
}
public:
vector<int> KDistanceNodes(Node* root, int target, int k)
{
vector<int> ans;
Node* targetNode = findTargetNode(root, target);
addNodesBelowAtK(targetNode, k, ans);
addNodesOnAncestorAtK(root, targetNode, k, ans);
sort(ans.begin(), ans.end());
return ans;
}
};