题意:我有一个树,求距离一个树木节点距离为k的节点值有哪些
输入输出
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/
分析:首先这道题的思路建图+bfs没有更好的思路了
cpp
/**
* 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:
unordered_map<int, vector<int>> graph;
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
construct(root);
queue<int> q;
unordered_set<int> visited;
vector<int> ret;
q.push(target->val);
int level = 0;
while(q.size()) {
int len = q.size();
for(int i = 0; i < len; i++) {
int node = q.front();
q.pop();
visited.insert(node);
if (level == k) {
ret.push_back(node);
}
for (auto e : graph[node]) {
if (!visited.count(e)) {
q.push(e);
}
}
}
level += 1;
}
return ret;
}
void construct(TreeNode* root) {
if(!root) {
return;
}
if (root->left) {
graph[root->val].push_back(root->left->val);
graph[root->left->val].push_back(root->val);
construct(root->left);
}
if (root->right) {
graph[root->val].push_back(root->right->val);
graph[root->right->val].push_back(root->val);
construct(root->right);
}
}
};