leetcode 863. All Nodes Distance K in Binary Tree(二叉树中距离K的节点)

Fluent温度超限调试:从能量方程到网格优化的实战指南 本文深入解析Fluent中温度超限问题的诊断与解决方法,从能量方程机制到网格优化策略,提供实战指南。通过分析温度与焓的换算关系,探讨典型场景如能量方程发散、局部网格质量差等,并给出五步调试法及高级命令应用,帮助工程师有效解决温度计算异常问题。 阅读详情

We are given a binary tree (with root node root), a target node, and an integer value K.

Return a list of the values of all nodes that have a distance K from the target node. The answer can be returned in any order.

Example 1:

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

Output: [7,4,1]

Explanation:
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.
在这里插入图片描述
Note that the inputs “root” and “target” are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.

给出一个二叉树,一个target节点,找出所有到target距离为K的节点。

思路:
参考了方法,两种思路

1 转化为无向图,用BFS
先把二叉树转为无向图,因为每个边都是双向的,所以要用一个HashSet保存访问过的node。
然后用BFS保存K步的node

class Solution {
    HashMap<TreeNode, List<TreeNode>> graph = new HashMap<>();
    
    public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
        List<Integer> result = new ArrayList<>();
        buildGraph(null, root);
        
        Queue<TreeNode> queue = new LinkedList<>();
        HashSet<TreeNode> visited = new HashSet<>();
        queue.add(target);
        visited.add(target);
        int k = 0;
        
        while(!queue.isEmpty() && k <= K) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if(k == K) result.add(node.val);
                for(TreeNode child : graph.get(node)) {
                    if(visited.contains(child)) continue;
                    queue.offer(child);
                    visited.add(child);
                }
            }
            k++;
        }
        return result;
    }
    
    void buildGraph(TreeNode root, TreeNode child) {
        if(root != null) {
          if(!graph.containsKey(root)) {
            List<TreeNode> tmp = new ArrayList<>();
            graph.put(root, tmp);
          }
        
          if(child != null) {
            graph.get(root).add(child);
            if(!graph.containsKey(child)) {
                List<TreeNode> tmp = new ArrayList<>();
                graph.put(child, tmp);
            }
            graph.get(child).add(root);
                        
          }
        } else {
        //root本身要建一个空的list,否则会出现NullPointerException
            List<TreeNode> tmp = new ArrayList<>();
            graph.put(child, tmp);
        }
        if(child.left != null) buildGraph(child, child.left);
        if(child.right != null) buildGraph(child, child.right);        
    }
}

2 树的中序遍历递归
中序遍历要做两件事情,第一,要找到target的位置,第二,找到距离target为K的node

中序遍历不像无向图那样是双向的,它从上到下遍历,所以收集距离target为K的node时,只收集某个root下面的节点,不会再往上走。

那么如果像Example中那样,target在左子树,但是root.right中也有目标怎么办。
这时可以找到root.left到target的距离,设这个距离是dis_left,那么root到target的距离就是dis_left+1。root到root.right的距离是1,所以root.left到root.right的距离是dis_left+2。那么只需要向下收集 到root.right距离为K - (dis_left+2)的node就行了。

所以需要一个函数,又能中序遍历找target,又能返回target到当前root的距离。而且要用-1表示没有找到target。
还需要一个中序遍历向下收集距离root为d的node的函数,因为返回了距离之后又要再次向下找node
这两个函数都是在遍历过程中一旦发现距离target为K的node,就保存到结果list中。

class Solution {
    List<Integer> result = new ArrayList<>();
    public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
        if(root == null) return result;
        distance(root, target, K);
        return result;
    }
    
    int distance(TreeNode root, TreeNode target, int K) {
        if(root == null) return -1;
        if(root.val == target.val) {
            collect(target, K);
            return 0;
        }
        int left = distance(root.left, target, K);
        int right = distance(root.right, target, K);
        
        if(left >= 0) {
            if(left == K-1) result.add(root.val);
            collect(root.right, K-left-2);
            return (left+1);
        }
        if(right >= 0) {
            if(right == K-1) result.add(root.val);
            collect(root.left, K-right-2);
            return (right+1);
        }
        return -1;
    }
    
    void collect(TreeNode root, int d) {
        if(root == null || d < 0) return;
        if(d == 0) result.add(root.val);
        collect(root.left, d-1);
        collect(root.right, d-1);
    }
}

还有一种是用一个map装每个点和它到target的距离,
target本身到自己的距离是0,其他的依次+1,
统计好之后再用dfs遍历节点,当距离为k时装入结果。

class Solution {
    public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        pathLength(map, root, target);
        List<Integer> res = new ArrayList<>();
        dfs(res, map, k, root, 0);
        return res;
    }

    private void dfs(List<Integer> res, Map<Integer, Integer> map, int k, TreeNode curr, int l) {
        if (curr == null) return;
        if (map.containsKey(curr.val)) l = map.get(curr.val);
        if (l == k) res.add(curr.val);
        dfs(res, map, k, curr.left, l + 1);
        dfs(res, map, k, curr.right, l + 1);
    }

    private int pathLength(Map<Integer, Integer> map, TreeNode curr, TreeNode target) {
        if (curr == null) return -1;
        if (curr == target) {
            map.put(curr.val, 0);
            return 1;
        }

        int left = pathLength(map, curr.left, target);
        if (left > 0) {
            map.put(curr.val, left);
            return left + 1;
        }

        int right = pathLength(map, curr.right, target);
        if (right > 0) {
            map.put(curr.val, right);
            return right + 1;
        }

        return -1;
    }
}
7.12真题华为OD机试真题 新系统 - 字符串压缩编码 (Java/Py/C/C++/Js/Go) 7.12真题华为OD机试真题 新系统 - 字符串压缩编码 (Java/Py/C/C++/Js/Go) 阅读详情

相关推荐

Cesium实战:如何在前端直接渲染TIFF影像(附完整代码与避坑指南)

本文详细介绍了如何在前端利用Cesium直接加载和渲染TIFF影像的完整技术方案。针对TIFF格式的地理影像数据,文章提供了从文件解析、坐标转换到像素处理与Cesium集成的全流程代码实现,并分享了性能优化与常见问题的避坑指南,帮助开发者高效实现三维地理可视化。

weixin_29290947的博客 327

863. All Nodes Distance K in Binary Tree [JavaScript]

一、题目   We are given a binary tree (with root node root), a target node, and an integer value K.   Return a list of the values of all nodes that have a distance K from the target node. The answer can ...

descire 237

风控要略-互联网业务反欺诈之路(一)

当前中国互联网安全产业答题可以分为基础安全和业务安全两个领域。从互联网诞生至2014年,互联网安全行业关注的热点基本都聚焦在网络安全、系统安全和应用安全这个三大基础安全领域上,“DDOS“(分布式拒绝服务攻击)1、“漏洞“、“拖库“2和“挂马“3等大家耳熟能详的术语也是从这些领域中衍生出来的。2014年前后,随着互联网业务的爆炸式发展,黑产团伙开始从“攻击渗透系统“的传统套路进化到“利用业务风控确实进行大规模牟利“的模式,并且逐渐形成规模庞大、分工明确的黑色产业链。

Despacito1006的博客 1026

863. All Nodes Distance K in Binary Tree

Loading... 思路:先找到父,然后做类似爆炸的寻找,看成图去找 思路2还没写:1 用O(n)把树打成数组 ,转换过程中如果找到target 就记录数组下标 2 根据当前target 进行运算 找 父节点 左右叶子节点,带入k 当k为0 说明算出一个解 3 循环get解-也就是数组下标,不为空就是有解 /** * Definition for a binary tree node. * public class TreeNode { * int val; * Tr...

我思故我在 318

C++ 类

本文介绍了C++中类的核心概念和使用方法。

weixin_54859557的博客 1023

Python高效转换病理图像:从mrxs到SVS的完整实践指南

本文提供了使用Python将数字病理切片从mrxs格式高效转换为SVS格式的完整实践指南。针对mrxs格式兼容性差的问题,文章详细解析了基于openslide和tifffile库的核心转换流程,并重点分享了应对大内存消耗的优化方案与流式处理技巧,确保转换后的SVS文件保留多分辨率金字塔结构,兼容主流病理分析工具。

weixin_29051811的博客 562

All Nodes Distance K in Binary Tree

We are given a binary tree (with root noderoot), atargetnode, and an integer valueK. Return a list of the values of allnodes that have a distanceKfrom thetargetnode. The answer can be retur...

leetcode 解题思路 383

Arduino程序设计(十四)舵机控制实验(SG90)

本文介绍SG90舵机控制原理及实验,主要内容有:1、介绍SG90舵机;2、舵机0°~180°来回转动;3、串口控制舵机转动固定角度。(1)舵机是一种位置(角度)伺服的驱动器。舵机只是一种通俗的叫法,其实质是一个伺服马达。在需要角度不断变化并可以保持的控制系统中应用广泛。如遥控机械人、飞机模型等。(2)舵机的转动角度为0~180°,其内部结构包括电机,控制电路和机械结构三部分。电机有三根线引出,分别接VCC、GNG和信号线。

Alice的博客 1万+

LeetCode //C - 863. All Nodes Distance K in Binary Tree

Problem Summary: Given a binary tree, a target node, and an integer k, the task is to find all nodes at distance k from the target node. Nodes can be located in any direction (children or ancestors) from the target. Key Solution Steps: Parent Mapping: Perf

Made in Code 1054

【自然语言处理(NLP)实战】LSTM网络实现中文文本情感分析(手把手与教学超详细)

在当今数字化时代,人们在社交媒体、评论平台以及各类在线交流中产生了海量的文本数据。这些数据蕴含着丰富的情感信息,从而成为了深入理解用户态度、市场趋势,甚至社会情绪的宝贵资源。自然语言处理(NLP)的发展为我们提供了强大的工具,使得对文本情感进行分析成为可能。在这个领域中,长短时记忆网络(LSTM)凭借其能够捕捉文本序列中长距离依赖关系的能力,成为了情感分析任务中的一项重要技术。通过详细的步骤和示例代码,深入了解如何处理中文文本数据、构建LSTM模型、进行训练和评估。

halo的博客 2万+

【思博伦】史上最详细Spirent TestCenter测试仪2544套件使用图文教程精讲!图解超赞超详细!!!

Avalanche测试仪使用指南 摘要:本文介绍了Avalanche测试仪的基本配置和使用方法。该测试仪采用Linux内核系统,通过端口模拟客户端与服务器端,支持HTTP、DNS、FTP等多种协议。文章详细讲解了管理IP配置、端口占用、项目创建、客户端/服务器端的参数设置(包括负载模拟、行为配置、网段设置等),以及测试执行和结果查看的全流程。特别针对HTTP测试,说明了测试前的组网准备和注意事项,包括IP地址规划、License申请等。同时提供了2544套件的时延和吞吐量测试方法,包括参数配置技巧和结果分析

风云说通信 2333

Leetcode 863 All Nodes Distance K in Binary Tree

Leetcode 863 All Nodes Distance K in Binary Tree Map<TreeNode, TreeNode> parent; If we know the parent of every node x, we know all nodes that are distance 1 from x. We can then perform a BFS ...

weixin_43876597的博客 129

Simulink实例--电动汽车充电站与微电网协同运行仿真

​电网负荷剧增:单站1000台车同时充电需150MW功率(超配电网容量30%)​能源孤岛问题:传统充电站仅作为单向负荷,无法参与电网调频​可再生能源消纳:光伏/风电波动导致充电站功率波动±40%​多目标矛盾:充电效率、电网稳定性、设备寿命的协同优化​节能效果:每百万辆车年节电1.8GWh​成本回收:投资回报周期<4年(IRR>25%)​减排效益:每年减少CO₂排放12万吨。

xiaoheshang_123的博客 332

[leetcode] 863. All Nodes Distance K in Binary Tree

Description We are given a binary tree (with root node root), a target node, and an integer value K. Return a list of the values of all nodes that have a distance K from the target node. The answer c...

Learning from the mistakes 301

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

LeetCode:863. All Nodes Distance K in Binary Tree

很有意思的一道树的题目了: 1.自己的做法。 首先是自己想出来的。自己拿个图画一下就知道了:找到与target相距K的节点,要么是target的子节点,要么是target的祖先节点以及它们的子节点当中去找。 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode ...

weixin_43462819的博客 180

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

LeetCode解题分享:863. All Nodes Distance K in Binary Tree

Problem We are given a binary tree (with root node root), a target node, and an integer value K. Return a list of the values of all nodes that have a distance K from the target node. The answer can b...

DaVinciL的博客 509

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

LeetCode 863. All Nodes Distance K in Binary Tree

原题链接在这里:https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/ 题目: We are given a binary tree (with root noderoot), atargetnode, and an integer valueK. Return a list of the values o...

weixin_30642305的博客 157

863. All Nodes Distance K in Binary Tree [Medium] 树和BFS

863. All Nodes Distance K in Binary Tree 863. All Nodes Distance K in Binary Tree 先构建图 # Definition for a binary tree node. # class TreeNode(object): # def __init__(se...

qq_35319215的博客 166

LC 863. All Nodes Distance K in Binary Tree

给定一个二叉树和一个目标节点,返回与目标节点距离K的所有节点集合。

ok1382038的博客 414

【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)

【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/all-nodes-distan...

负雪明烛 5904

【Leetcode】863. All Nodes Distance K in Binary Tree 863. 二叉树中所有距离为 K 的结点

解法 树型DP solve(root)返回target距离root的父亲 有多远,如果返回-1表示target不在root里 假如我们得到了L=solve(root.left),假如L!=-1,说明target在左子树,且距离root那么只要把右子树里距离root的距离是K-L的结点加入答案就行了,右边不需要再遍历了 假如我们得到了R=solve(root.right),操作也是类似的 #...

lemonmillie的博客 272

[LeetCode] 863. All Nodes Distance K in Binary Tree

题:https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/ 题目大意 求给树中,距给定 结点 指定长度的 所有结点的val 思路 将树变为图,然后 bfs。对于树,记录每个结点的父结点,使用map。 /** * Definition for a binary tree node. * public class Tre...

u013383813的博客 193

[Leetcode] 863. All Nodes Distance K in Binary Tree 找出距离某个点距离为k的所有的点

863.All Nodes Distance K in Binary Tree (题目链接) Medium We are given a binary tree (with root noderoot), atargetnode, and an integer valueK. Return a list of the values of allnodes that have a distanceKfrom thetargetnode. The answer can be retu...

热爱编程,热爱技术 249

leetcode-863. All Nodes Distance K in Binary Tree

We are given a binary tree (with root noderoot), atargetnode, and an integer valueK. Return a list of the values of allnodes that have a distanceKfrom thetargetnode. The answer can be retur...

hello world 203
上一篇: leetcode 814. Binary Tree Pruning(修剪二叉树)
下一篇: leetcode 865. Smallest Subtree with all the Deepest Nodes(包含最深点的最小子树)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址