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);
        }
    }  
};
相关推荐
代码不停10 分钟前
Java前缀和算法题目练习
java·开发语言·算法
courniche14 分钟前
分组密码常见结构简介
算法·密码学
涤生z18 分钟前
list.
开发语言·数据结构·c++·学习·算法·list
xxxxxxllllllshi21 分钟前
Java中Elasticsearch完全指南:从零基础到实战应用
java·开发语言·elasticsearch·面试·职场和发展·jenkins
茜茜西西CeCe37 分钟前
数字图像处理-图像增强(2)
人工智能·算法·计算机视觉·matlab·数字图像处理·图像增强·陷波滤波器
薰衣草23331 小时前
hot100练习-11
算法·leetcode
地平线开发者1 小时前
征程 6 | 工具链如何支持 Matmul/Conv 双 int16 输入量化?
人工智能·算法·自动驾驶
甄心爱学习2 小时前
数值计算-线性方程组的迭代解法
算法
stolentime2 小时前
SCP2025T2:P14254 分割(divide) 题解
算法·图论·组合计数·洛谷scp2025
Q741_1472 小时前
C++ 面试基础考点 模拟题 力扣 38. 外观数列 题解 每日一题
c++·算法·leetcode·面试·模拟