[Problem]
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/
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.
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
Chinese translation:
題目是給你一個Tree,還有當中特定特定的一個node,請回答哪些人和此node距離為k。
請注意即使在不同子樹的node也要被納入考量,如例子中的node '1'。
[Solution]
Transform tree into graph. Execute BFS on graph to find level K nodes.
This solution is pretty simple and easy to understand.
1.You Transform the tree into a graph. In the graph each node have pointer to their neighbors.
2.Execute BFS (starting from target node), find level K nodes
Let's write codes.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode2{
int val;
TreeNode2 *left;
TreeNode2 *right;
TreeNode2 *father;
TreeNode2(int x) : val(x), left(NULL), right(NULL), father(NULL)
{}
};
class Solution {
public:
TreeNode2* targetNode2;
TreeNode* targetNode;
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
vector<int> ans;
targetNode2=NULL;
targetNode=target;
//build the graph of original tree
buildGraph(root,NULL);
//execute BFS for that tree
BFS(targetNode2, ans, K);
return ans;
}
void BFS(TreeNode2* start, vector<int>& ans, int K)
{
if(start==NULL) return;
queue<TreeNode2*> q;
unordered_map<int,int> visited;
q.push(start);
visited[start->val]++;
int cnt=0;
while(!q.empty() && cnt <= K){
int num=q.size();
for(int i=0;i<num;i++){
TreeNode2* cur=q.front();q.pop();
if(cnt==K)
ans.push_back(cur->val);
if(cur->left && visited[cur->left->val]++==0)
q.push(cur->left);
if(cur->right && visited[cur->right->val]++==0)
q.push(cur->right);
if(cur->father && visited[cur->father->val]++==0)
q.push(cur->father);
}
cnt++;
}
}
TreeNode2* buildGraph(TreeNode* root, TreeNode2* father)
{
if(root==NULL) return NULL;
TreeNode2* root2=new TreeNode2(root->val);
root2->father=father;
root2->left=buildtree(root->left,root2);
root2->right=buildtree(root->right,root2);
if(targetNode==root)
targetNode2=root2;
return root2;
}
};
Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.