难度:中等。
标签:二叉树,深度优先搜索,广度优先搜索。
先找出根节点到target的路径上所有的点,将找与target的距离为k的点转换为找与路径上的点距离为find_dis的点。
注意不要重复判断。
正确解法:
/**
* 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 {
bool getPath(TreeNode* cur, TreeNode* target, vector<TreeNode*>& path){
if(cur == nullptr)return false;
if(cur == target)return true;
if(cur->left != nullptr){
path.emplace_back(cur->left);
if(getPath(cur->left, target, path))return true;
path.pop_back();
}
if(cur->right != nullptr){
path.emplace_back(cur->right);
if(getPath(cur->right, target, path))return true;
path.pop_back();
}
return false;
}
void findNode(TreeNode* cur, int dis, vector<int>& found, TreeNode* node){
if(cur == nullptr || cur == node)return;
if(dis == 0){
found.emplace_back(cur->val);
return;
}
findNode(cur->left, dis - 1, found, node);
findNode(cur->right, dis - 1, found, node);
}
int max(int a, int b){
return a > b ? a : b;
}
int min(int a, int b){
return a < b ? a : b;
}
public:
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
unordered_map<TreeNode*, int> maps;
vector<TreeNode*> path;
path.emplace_back(root);
getPath(root, target, path);
vector<int> ans;
int begin = max(path.size() - k - 1, 0);
for(int i = begin; i < path.size(); ++i){
int find_dis = k - (path.size() - i - 1);
if(find_dis == 0)ans.emplace_back(path[i]->val);
else if(find_dis > 0){
if(i + 1 != path.size())findNode(path[i], find_dis, ans, path[i + 1]);
else findNode(path[i], find_dis, ans, nullptr);
}
}
return ans;
}
};
结果: