1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
all-nodes-distance-k-in-binary-tree.cpp 1.32 KB
一键复制 编辑 原始数据 按行查看 历史
// 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:
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
unordered_map<int, vector<int>> neighbors;
dfs(nullptr, root, &neighbors);
vector<int> bfs{target->val};
unordered_set<int> lookup{target->val};
for (int i = 0; i < K; ++i) {
vector<int> curr;
for (const auto& node : bfs) {
for (const auto& nei : neighbors[node]) {
if (!lookup.count(nei)) {
curr.emplace_back(nei);
lookup.emplace(nei);
}
}
}
swap(bfs, curr);
}
return bfs;
}
private:
void dfs(TreeNode *parent, TreeNode *child,
unordered_map<int, vector<int>> *neighbors) {
if (!child) {
return;
}
if (parent) {
(*neighbors)[parent->val].emplace_back(child->val);
(*neighbors)[child->val].emplace_back(parent->val);
}
dfs(child, child->left, neighbors);
dfs(child, child->right, neighbors);
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助