863.二叉树中所有距离为K的节点

一、考察知识点

本题和二叉树关系也不大,关键是二叉树如何转化为无向图,与无向图的广度有限遍历的应用。

二、代码

class Solution {
public:
    vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
        buildGraph(NULL, root);
        vector<int> ans;
        unordered_set<TreeNode*> seen;
        queue<TreeNode*> q;
        seen.insert(target);
        q.push(target);
        int cur_k = 0;
        while(!q.empty() && cur_k <= k){
            int s = q.size();
            while(s--){
                TreeNode* node = q.front();
                q.pop();
                if (cur_k == k) ans.push_back(node->val);
                for(TreeNode* child : g[node]){
                    if(seen.count(child)) continue;
                    q.push(child);
                    seen.insert(child);
                }
            }
            ++cur_k;
        }
        return ans;
    }
private:
    unordered_map<TreeNode*, vector<TreeNode*>> g;
    void buildGraph(TreeNode* parent, TreeNode* child){
        if(parent){
            g[parent].push_back(child);
            g[child].push_back(parent);
        }
        if (child->left) buildGraph(child, child->left);
        if (child->right) buildGraph(child, child->right);
    }
};

1.将二叉树转化为无向图。

2.进行广度优先遍历,将深度为2的所有元素push到ans中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值