forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0742.cpp
41 lines (39 loc) · 1.08 KB
/
0742.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
class Solution
{
public:
int findClosestLeaf(TreeNode* root, int k)
{
_start = nullptr;
buildGraph(root, nullptr, k);
queue<TreeNode*> q;
q.push(_start);
unordered_set<TreeNode*> visited;
while (!q.empty())
{
int size = q.size();
for (int i = 0; i < size; ++i)
{
TreeNode* cur = q.front(); q.pop()
visited.insert(cur);
if (!cur->left and !cur->right) return cur->val;
for (TreeNode* node : _graph[cur])
if (!visited.count(node)) q.push(node);
}
}
}
private:
unordered_map<TreeNode*, vector<TreeNode*>> _graph;
TreeNode* _start;
void buildGraph(TreeNode* node, TreeNode* parent, int k)
{
if (!node) return;
if (node->val == k) _start = node;
if (parent)
{
_graph[node].push_back(parent);
_graph[parent].push_back(node);
}
buildGraph(node->left, node, k);
buildGraph(node->right, node, k);
}
};