-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path742.cpp
More file actions
49 lines (48 loc) · 1.6 KB
/
742.cpp
File metadata and controls
49 lines (48 loc) · 1.6 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_set<int> leaveSt;
void dfs(TreeNode* node, TreeNode* parent, unordered_map<int, vector<int>>& adjacency) {
if (node == nullptr) return;
if (node->left == nullptr && node->right == nullptr) leaveSt.insert(node->val);
if (parent != nullptr) {
adjacency[node->val].push_back(parent->val);
adjacency[parent->val].push_back(node->val);
}
dfs(node->left, node, adjacency);
dfs(node->right, node, adjacency);
}
int findClosestLeaf(TreeNode* root, int k) {
unordered_map<int, vector<int>> adjacency;
dfs(root, nullptr, adjacency);
// bfs
queue<int> q;
unordered_set<int> st;
q.push(k);
st.insert(k);
while (!q.empty()) {
int n = q.size();
for (int i = 0; i < n; ++i) {
int node = q.front();
q.pop();
if (leaveSt.find(node) != leaveSt.end()) return node;
for (auto& neighbor : adjacency[node]) {
if (st.find(neighbor) != st.end()) continue;
q.push(neighbor);
st.insert(neighbor);
}
}
}
return -1;
}
};