forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
closest-leaf-in-a-binary-tree.cpp
63 lines (60 loc) · 1.75 KB
/
closest-leaf-in-a-binary-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
// Time: O(n)
// Space: O(n)
/**
* 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 {
public:
int findClosestLeaf(TreeNode* root, int k) {
unordered_map<int, vector<int>> neighbors;
unordered_set<int> leaves;
traverse(root, &neighbors, &leaves);
vector<int> q{k};
unordered_set<int> lookup{k};
while (!q.empty()) {
vector<int> next_q;
for (const auto& u : q) {
if (leaves.count(u)) {
return u;
}
for (const auto& v : neighbors[u]) {
if (lookup.count(v)) {
continue;
}
lookup.emplace(v);
next_q.emplace_back(v);
}
}
swap(q, next_q);
}
return 0;
}
private:
void traverse(TreeNode *node,
unordered_map<int, vector<int>> *neighbors,
unordered_set<int> *leaves) {
if (!node) {
return;
}
if (!node->left && !node->right) {
leaves->emplace(node->val);
return;
}
if (node->left) {
(*neighbors)[node->val].emplace_back(node->left->val);
(*neighbors)[node->left->val].emplace_back(node->val);
traverse(node->left, neighbors, leaves);
}
if (node->right) {
(*neighbors)[node->val].emplace_back(node->right->val);
(*neighbors)[node->right->val].emplace_back(node->val);
traverse(node->right, neighbors, leaves);
}
}
};