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);
        }
    }  
};
相关推荐
严文文-Chris2 分钟前
【监督学习常用算法总结】
学习·算法
feifeigo1234 分钟前
电池的荷电状态(SOC)估计
算法
博语小屋1 小时前
力扣 15.三数之和(medium)(双指针)
算法·leetcode·职场和发展
无敌最俊朗@1 小时前
双指针-力扣hot100-移动零.283
算法·leetcode·职场和发展
练习时长一年1 小时前
LeetCode热题100(腐烂的橘子)
算法·leetcode·职场和发展
Тиё Сиротака7 小时前
红包分配算法的严格数学理论与完整实现
算法
potato_may7 小时前
链式二叉树 —— 用指针构建的树形世界
c语言·数据结构·算法·链表·二叉树
java修仙传8 小时前
每日一题,力扣560. 和为 K 的子数组
算法·leetcode
ada7_8 小时前
LeetCode(python)——148.排序链表
python·算法·leetcode·链表
点云SLAM8 小时前
点云配准算法之-Voxelized GICP(VGICP)算法
算法·机器人·gpu·slam·点云配准·vgicp算法·gicp算法