-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAllNodesDistanceKinBinaryTree_863.cpp
84 lines (67 loc) · 2.3 KB
/
AllNodesDistanceKinBinaryTree_863.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
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 863. All Nodes Distance K in Binary Tree
~ Link : https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
unordered_map<int, TreeNode*> parent;
private:
void getParentOfAllNodes(TreeNode *root, TreeNode *parentNode) {
if (!root)
return;
parent[root -> val] = parentNode;
getParentOfAllNodes(root -> left, root);
getParentOfAllNodes(root -> right, root);
}
public:
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
vector<int> res;
getParentOfAllNodes(root, NULL);
queue<TreeNode*> todo;
todo.push(target);
unordered_map<int, bool> visited;
visited[target -> val] = true;
while (!todo.empty()) {
int lvl = todo.size();
for (int i = 0; i < lvl; ++i) {
TreeNode *curr = todo.front();
todo.pop();
if (k == 0) {
res.emplace_back(curr -> val);
}
else {
TreeNode *currParent = parent[curr -> val];
// explore upwards
if (currParent != NULL && !visited[currParent -> val]) {
todo.push(currParent);
visited[currParent -> val] = true;
}
// explore left child
if (curr -> left && !visited[curr -> left -> val]) {
todo.push(curr -> left);
visited[curr -> left -> val] = true;
}
// explore right child
if (curr -> right && !visited[curr -> right -> val]) {
todo.push(curr -> right);
visited[curr -> right -> val] = true;
}
}
}
if (--k < 0)
break;
}
return res;
}
};
// T.C. - O(n)
// S.C. - O(n)