Leetcode 863All Nodes Distance K in Binary tree

题意:我有一个树,求距离一个树木节点距离为k的节点值有哪些

输入输出

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

Output: [7,4,1]

https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/

分析:首先这道题的思路建图+bfs没有更好的思路了

cpp 复制代码
/**
 * 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:
    unordered_map<int, vector<int>> graph;
    vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
        construct(root);
        queue<int> q;
        unordered_set<int> visited;
        vector<int> ret;
        q.push(target->val);
        int level = 0;
        while(q.size()) {
            int len = q.size();
            for(int i = 0; i < len; i++) {
                int node = q.front();
                q.pop();
                visited.insert(node);
                if (level == k) {
                    ret.push_back(node);
                }
                for (auto e : graph[node]) {
                    if (!visited.count(e)) {
                        q.push(e);
                    }
                }
            }
            level += 1;
        }
        return ret;
    }
    void construct(TreeNode* root) {
        if(!root) {
            return;
        }
        if (root->left) {
            graph[root->val].push_back(root->left->val);
            graph[root->left->val].push_back(root->val);
            construct(root->left);
        }
        if (root->right) {
            graph[root->val].push_back(root->right->val);
            graph[root->right->val].push_back(root->val);
            construct(root->right);
        }
    }  
};
相关推荐
艾莉丝努力练剑33 分钟前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途2 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
珊瑚里的鱼6 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
秋说6 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
lifallen7 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka
liupenglove7 小时前
自动驾驶数据仓库:时间片合并算法。
大数据·数据仓库·算法·elasticsearch·自动驾驶
python_tty8 小时前
排序算法(二):插入排序
算法·排序算法
然我8 小时前
面试官:如何判断元素是否出现过?我:三种哈希方法任你选
前端·javascript·算法
F_D_Z9 小时前
【EM算法】三硬币模型
算法·机器学习·概率论·em算法·极大似然估计
秋说9 小时前
【PTA数据结构 | C语言版】字符串插入操作(不限长)
c语言·数据结构·算法