-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclosest-leaf-in-a-binary-tree.cpp
71 lines (61 loc) · 1.78 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
64
65
66
67
68
69
70
71
//Runtime: 23 ms
class Solution {
public:
unordered_map<int, vector<int> > adj;
set<int>leafs;
void createGraph(TreeNode* root) {
if (!root)
return;
vector<int>t;
if (adj.find(root->val) == adj.end()) {
adj[root->val] = t;
}
if (!root->left && !root->right)
leafs.insert(root->val);
if (root->left) {
adj[root->val].push_back(root->left->val);
adj[root->left->val] = t;
adj[root->left->val].push_back(root->val);
}
if (root->right) {
adj[root->val].push_back(root->right->val);
adj[root->right->val] = t;
adj[root->right->val].push_back(root->val);
}
createGraph(root->left);
createGraph(root->right);
}
int findClosestLeaf(TreeNode* root, int k) {
createGraph(root);
int src = k;
int V = adj.size();
unordered_map<int, bool> vis;
unordered_map<int, int> dis;
int mindis = INT_MAX;
int ans;
vis[src] = 1;
dis[src] = 0;
if (leafs.find(src) != leafs.end()) return k;
queue<int> Q;
Q.push(src);
while (!Q.empty()) {
int t = Q.front();
Q.pop();
vector<int> list = adj[t];
for (int a : list) {
if (vis.find(a) == vis.end()) {
vis[a] = 1;
dis[a] = dis[t] + 1;
if (leafs.find(a) != leafs.end()) {
if (dis[a] < mindis) {
mindis = dis[a];
ans = a;
}
}
Q.push(a);
}
}
}
return ans;
}
};