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);
        }
    }  
};
相关推荐
QuZero33 分钟前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称40 分钟前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划
Felven1 小时前
B. Fair Numbers
数据结构·算法
人道领域1 小时前
【LeetCode刷题日记】93.复原IP地址
java·开发语言·算法·leetcode
jarreyer1 小时前
【算法记录1】模型训练问题
算法
Felven1 小时前
D. Friends and the Restaurant
算法
想吃火锅10051 小时前
【leetcode】165.比较版本号js
javascript·算法·leetcode
San813_LDD1 小时前
[量化]《浮点数比较的艺术:从内存布局到极致性能优化》
网络·算法
ysu_03141 小时前
leetcode数据结构与算法1~4
c语言·数据结构·学习·算法·leetcode
小欣加油1 小时前
leetcode2574 左右元素和的差值
数据结构·c++·算法·leetcode·职场和发展