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);
        }
    }  
};
相关推荐
Aspect of twilight38 分钟前
LeetCode华为2025年秋招AI大模型岗刷题(四)
算法·leetcode·职场和发展
有泽改之_8 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
im_AMBER8 小时前
Leetcode 74 K 和数对的最大数目
数据结构·笔记·学习·算法·leetcode
无敌最俊朗@8 小时前
STL-vector面试剖析(面试复习4)
java·面试·职场和发展
t198751288 小时前
电力系统经典节点系统潮流计算MATLAB实现
人工智能·算法·matlab
断剑zou天涯8 小时前
【算法笔记】蓄水池算法
笔记·算法
长安er8 小时前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
Benmao⁢9 小时前
C语言期末复习笔记
c语言·开发语言·笔记·leetcode·面试·蓝桥杯
唯道行9 小时前
计算机图形学·23 Weiler-Athenton多边形裁剪算法
算法·计算机视觉·几何学·计算机图形学·opengl
CoderYanger9 小时前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节