题目地址:
https://leetcode.com/problems/closest-leaf-in-a-binary-tree/
给定一棵二叉树,每个值都不相同。再给定一个值 k k k,问离值为 k k k的节点最近的叶子节点的值。题目保证值为 k k k的节点一定存在。如果有若干满足条件的解,则返回任意一个即可。
可以先用DFS建图,然后用BFS求一下最短路即可。代码如下:
class Solution {
public:
int findClosestLeaf(TreeNode* root, int k) {
unordered_map<int, vector<int>> g;
unordered_set<int> leaves;
dfs(root, nullptr, g, leaves);
if (leaves.count(k)) return k;
queue<int> q;
q.push(k);
unordered_set<int> vis{k};
while (q.size()) {
auto t = q.front();
q.pop();
for (auto& ne : g[t]) {
if (leaves.count(ne)) return ne;
if (!vis.count(ne)) {
vis.insert(ne);
q.push(ne);
}
}
}
return -1;
}
void dfs(TreeNode* t, TreeNode* p, unordered_map<int, vector<int>>& g,
unordered_set<int>& leaves) {
if (!t) return;
if (!t->left && !t->right) leaves.insert(t->val);
if (p) g[t->val].push_back(p->val);
if (t->left) {
g[t->val].push_back(t->left->val);
dfs(t->left, t, g, leaves);
}
if (t->right) {
g[t->val].push_back(t->right->val);
dfs(t->right, t, g, leaves);
}
}
};
时空复杂度 O ( n ) O(n) O(n)。