leetcode 863. All Nodes Distance K in Binary Tree

We are given a binary tree (with root node root), a target node, and an integer value K.

Return a list of the values of all nodes that have a distance K from the target node. The answer can be returned in any order.

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2

Output: [7,4,1]

Explanation:
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.

Note that the inputs “root” and “target” are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.

image

Note:

The given tree is non-empty.
Each node in the tree has unique values 0 <= node.val <= 500.
The target node is a node in the tree.
0 <= K <= 1000.

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(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

int vis[1000];
class Solution {
public:
queue<int> q;
//!!
vector<vector<int>> g=vector<vector<int>>(500);//沒有初始化vector的大小 不能直接赋值

vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
vector<int> ans;
buildpath(nullptr,root);
memset(vis,0,sizeof(vis));
q.push(target->val);
int k=0;
while(!q.empty()){
int size=q.size();
while(size--){
int t=q.front();
q.pop();
vis[t]=1;
if(k==K) ans.push_back(t);
for(int i=0;i<g[t].size();i++){
if(vis[g[t][i]]) continue;
q.push(g[t][i]);
}
}
k++;
}
return ans;
}
void buildpath(TreeNode *parent,TreeNode *child){
if(parent){
g[parent->val].push_back(child->val);
g[child->val].push_back(parent->val);
}
if(child->left) buildpath(child,child->left);
if(child->right) buildpath(child,child->right);

}
};