LeetCode 863. 二叉树中所有距离为 K 的结点(简易版)
原题链接
简单
作者:
haaai
,
2020-07-17 12:00:18
,
所有人可见
,
阅读 554
- 将从root到target的路线记录在deque中
- 从后向前从deque中取出节点,每次从所取节点往下做深度为i的dfs
- node_vis用来防止走重复的路线
/**
* 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> ans;
TreeNode* tar, *node_vis;
deque<TreeNode*> q;
bool dfs_findTar(TreeNode* node){
if (node == nullptr) return false;
q.push_back(node);
if (node == tar)
return true;
if (dfs_findTar(node->left)) return true;
if (dfs_findTar(node->right)) return true;
q.pop_back();
return false;
}
void dfs_down(TreeNode* node, int h){
if (node == nullptr) return;
if (h == 0)
ans.push_back(node->val);
if (node->right != node_vis) dfs_down(node->right, h-1);
if (node->left != node_vis) dfs_down(node->left, h-1);
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
tar = target;
dfs_findTar(root);
int cnt =-1;
while (q.size()){
cnt++;
auto t = q.back(); q.pop_back();
dfs_down(t, K - cnt);
node_vis = t;
}
return ans;
}
};