[Leetcode] 742. Closest Leaf in a Binary Tree

Leetcode 742.二叉树最近的叶子结点 题目描述 给定一个 每个结点的值互不相同 的二叉树,和一个目标值 k,找出树中与目标值 k 最近的叶结点。 这里,与叶结点 最近 表示在二叉树中到达该叶节点需要行进的边数与到达其它叶结点相比最少。而且,当一个结点没有孩子结点时称其为叶结点。 在下面的例子中,输入的树以逐行的平铺形式表示。实际上的有根树 root 将以TreeNode对象的形式给出。 示例 1: 输入: root = [1, 3, 2], k = 1 二叉树图示: 1 / \ 3 2 1 2 3 输出: 2 阅读详情

题目:

Given a binary tree where every node has a unique value, and a target key k, find the value of the nearest leaf node to target k in the tree.

Here, nearest to a leaf means the least number of edges travelled on the binary tree to reach any leaf of the tree. Also, a node is called a leaf if it has no children.

In the following examples, the input tree is represented in flattened form row by row. The actual root tree given will be a TreeNode object.

Example 1:

Input:
root = [1, 3, 2], k = 1
Diagram of binary tree:
          1
         / \
        3   2

Output: 2 (or 3)

Explanation: Either 2 or 3 is the nearest leaf node to the target of 1.

Example 2:

Input:
root = [1], k = 1
Output: 1

Explanation: The nearest leaf node is the root node itself.

Example 3:

Input:
root = [1,2,3,4,null,null,null,5,null,6], k = 2
Diagram of binary tree:
             1
            / \
           2   3
          /
         4
        /
       5
      /
     6

Output: 3
Explanation: The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.

Note:

  1. root represents a binary tree with at least 1 node and at most 1000 nodes.
  2. Every node has a unique node.val in range [1, 1000].
  3. There exists some node in the given binary tree for which node.val == k.

思路:

由于在题目中,要求“travel”不仅可以从父节点到子节点,而且还可以从子节点到父节点,所以实际上是把树作为一个图来处理了。那么我们怎么做呢?我们可以额外定义一个哈希表,建立从子节点到父节点的映射。然后就可以采用BFS方法,从值为k的节点开始遍历,找到第一个叶子结点,即为我们所求。

我开始实现的代码总是无法通过大数据测试,找不到原因。后来才发现,不同节点可能会被多次加入队列,造成了重复计算。所以我后来定义了另外一个哈希表,记录已经被访问过的节点。这样节点就不会被重复访问了,可以顺利通过所有测试数据。

代码:

/**
 * 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:
    int findClosestLeaf(TreeNode* root, int k) {
        TreeNode *node;
        unordered_map<TreeNode*, TreeNode*> parent;
        constructParent(root, parent, k, node);
        queue<pair<TreeNode*, int>> q;
        q.push(make_pair(node, 0));
        if (!node->left && !node->right) {
            return node->val;
        }
        unordered_set<TreeNode*> visited;
        visited.insert(node);
        while (!q.empty()) {
            node = q.front().first;
            int dist = q.front().second;
            if (!node->left && !node->right) {  // a leaf
                return node->val;
            }
            if (parent.count(node) > 0 && visited.count(parent[node]) == 0) {
                q.push(make_pair(parent[node], dist + 1));
                visited.insert(parent[node]);
            }
            if (node->left && visited.count(node->left) == 0) {
                q.push(make_pair(node->left, dist + 1));
                visited.insert(node->left);
            }
            if (node->right && visited.count(node->right) == 0) {
                q.push(make_pair(node->right, dist +1));
                visited.insert(node->right);
            }
            q.pop();
        }
        return -1;
    }
private:
    void constructParent(TreeNode* root, unordered_map<TreeNode*, TreeNode*> &parent, int k, TreeNode* &node) {
        if (root->val == k) {
            node = root;
        }
        if (root->left) {
            parent[root->left] = root;
            constructParent(root->left, parent, k, node);
        }
        if (root->right) {
            parent[root->right] = root;
            constructParent(root->right, parent, k, node);
        }
    }
};

从玩具到工业:手把手教你用Webots仿真Scara抓取(逆解实战篇) 本文详细介绍了如何在Webots仿真环境中实现Scara机械臂的逆解计算与抓取操作,涵盖从环境配置、逆运动学算法到轨迹规划与实时控制的完整流程。通过实战案例演示,帮助读者掌握机械臂逆解的核心技术,并应用于工业自动化场景,提升Scara机械臂的编程与控制能力。 阅读详情

相关推荐

无人自行车平衡控制:最小二乘法动态零点拟合实践

本文探讨了无人自行车平衡控制中动态零点的重要性及实现方法。通过最小二乘法拟合车头角度与ROL值的线性关系,解决了固定零点在转向时导致的稳定性问题。实践表明,动态零点拟合能显著提升系统平衡稳定性并降低能耗。

uran的专栏 660

【LeetCode - 742】二叉树最近的叶节点

【中等】树

学哥斌的博客 1221

CPU核心、die和package的区别:从硬件小白到高手的进阶指南

本文深入浅出地解析了CPU核心、Die与Package的核心概念与区别,是硬件爱好者从入门到精通的实用指南。文章从硅晶圆制造讲起,阐述了物理核心与逻辑线程(如超线程技术)的工作原理,并详细介绍了封装(Package)的作用与多Die模块化设计。最后,结合实际应用场景,提供了选购、性能解读与优化调优的实用建议。

pz89012345的博客 201

【Leetcode】742. Closest Leaf in a Binary Tree

题目地址: https://leetcode.com/problems/closest-leaf-in-a-binary-tree/ 给定一棵二叉树,每个值都不相同。再给定一个值kkk,问离值为kkk的节点最近的叶子节点的值。题目保证值为kkk的节点一定存在。如果有若干满足条件的解,则返回任意一个即可。 可以先用DFS建图,然后用BFS求一下最短路即可。代码如下: import java.util.*; public class Solution { // 存值为k的节点 private Tre

数学、算法爱好者的博客 293

从零部署DeepSeek V4 Flash:NVIDIA DGX Spark实战指南

GPU加速计算已成为现代人工智能基础设施的核心,其原理是通过并行处理架构大幅提升深度学习模型的训练与推理效率。在AI工程实践中,NVIDIA GPU凭借CUDA生态和专用驱动栈,为大规模语言模型部署提供了硬件基础。本文聚焦于企业级AI服务器部署场景,针对NVIDIA DGX Spark多节点系统的硬件初始化、驱动兼容性配置、容器化部署等关键环节,提供从系统层到应用层的完整解决方案。通过vLLM推理框架的实战配置,演示如何将DeepSeek V4 Flash模型高效部署于多GPU环境,涵盖Tensor Par

weixin_32296621的博客 375

DAZ STUDIO 快速渲染技巧

DAZ STUDIO 快速渲染技巧: 本文将向您展示几个快速渲染技巧。您将学习如何使您的Daz Iray渲染和照明在Daz工作室内更快。 当你有一个大场景,这可能需要很多小时进行渲染。 但是如果你想大幅度降低渲染时间呢?这篇文章的提示应该能让你达到这个目标。 首先,我们需要弄清楚一件事——没有“完美的环境或设置”这样的东西。是因为渲染设置是高度个性化和主观性的东西,这主要取决于场景和硬件。如果你有一个功能强大的计算机,你可以允许更多的低渲染时间,反之亦然。因此,一切都取决于您尝试渲染的对象和机器。

DAZSTUDIO的博客 9644

Leetcode 742:Closest Leaf in a Binary Tree(超详细的解法!!!)

Given a binary tree where every node has a unique value, and a target key k, find the value of the nearest leaf node to target k in the tree. Here, nearest to a leaf means the least number of edges tr...

coordinate的博客 1321

3种六轴IMU姿态解算算法对比:互补滤波、Mahony与卡尔曼滤波性能实测

本文深入对比了三种六轴IMU姿态解算算法:互补滤波、Mahony与卡尔曼滤波的性能表现。通过实测数据分析了各算法在精度、计算复杂度和适用场景上的差异,为无人机、机器人等运动控制系统提供了选型建议。重点探讨了六轴陀螺仪与加速度传感器的数据融合技术,帮助开发者根据项目需求选择最优解算方案。

weixin_29054245的博客 334

742. Closest Leaf in a Binary Tree的思路

题目大意是,找到最临近给定节点的叶节点,例如 1 / \ 2 3 / 4 / 5 / 6 给定2的话,最近的是3,给定4的话,最近的是6。 思路:题目中,树的结构并不利于寻找答案,需要把树的结构转换成图,然后通过广度优先搜索,可

dong_beijing的博客 505

STM32cubemx配置驱动DHT11模块

本篇文章将带大家学习使用DHT11湿温度模块,使用这个模块可以获取当前的温度和湿度数据。DHT11可以用于智能家居,蔬菜大棚等项目当中适用范围广。DHT11 是一种数字式温湿度传感器,由杜邦公司推出。它可以测量环境中的温度和湿度,并将测量结果以数字形式传输给微控制器或其他电子设备,适用于通过数字信号读取环境温湿度的应用场景。DHT11 传感器使用单总线数据交换协议,可以通过一个 I/O 引脚进行控制和数据传输。

m0_49476241的博客 5912

AndroidKiller之APK 编译失败,无法继续下一步签名【BUG解决】【App反向解析】

文章目录项目场景:问题描述原因分析:解决方案:BUG解决 项目场景: AndroidKiller: 在反向解析APP包时报错:APK 编译失败,无法继续下一步签名。 网上很多方法都是无效的哈,我追究原因发现,这个bug的出现大部分情况都是因为Apktool的问题。 此方法:百分之百解决此bug! 错误如下: 问题描述 APK 编译失败,无法继续下一步签名! 原因分析: Apktool版本不适配的问题,现在的技术更新换代太快,我们安装AndroidKiller的时候,有时候不是官方渠道的话,他的版本是非常

一键难忘的博客 2万+

Leetcode 742. Closest Leaf in a Binary Tree

Leetcode 742. Closest Leaf in a Binary Tree Approach #1: Convert to Graph 把树转换为以k节点为中心的图,从k节点开始层序遍历,返回最先遇到的叶子结点。 class Solution { public int findClosestLeaf(TreeNode root, int k) { Map<TreeNode, List<TreeNode>> graph = new HashMap()

weixin_43876597的博客 176

【GameFramework框架内置模块】15、场景(Scene)

场景(Scene)模块,提供场景管理的功能,负责场景的加载、卸载、切换和管理。可以方便地管理不同场景之间的切换以及不同场景之间的信息传递。

优快云博客专家,Unity3D高级软件工程师,《Unity 3D从入门到实战》作者。 1882

LeetCode 742. Closest Leaf in a Binary Tree

原题链接在这里:https://leetcode.com/problems/closest-leaf-in-a-binary-tree/ 题目: Given a binary treewhere every node has a unique value, and a target keyk, find the value of the nearest leaf node to targe...

weixin_30648963的博客 146

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

LeetCode | 742. Closest Leaf in a Binary Tree12_16

742. Closest Leaf in a Binary Tree My SubmissionsBack to Contest ·       User Accepted:351 ·       User Tried:667 ·       Total Accepted:356 ·       Total Submissions:1586 ·       Difficulty

u012737193的博客 390

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

leetcode_742. Closest Leaf in a Binary Tree ? 待解决

Given a binary tree where every node has a unique value, and a target key k, find the value of the closest leaf node to target k in the tree.Here, closest to a leaf means the least number of edges trav

wjheha的博客 320

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

742. Closest Leaf in a Binary Tree查找最近的叶子节点

[抄题]: Given a binary treewhere every node has a unique value, and a target keyk, find the value of the nearest leaf node to targetkin the tree. Here,nearestto a leaf means the least number of ...

weixin_30699463的博客 107

742. Closest Leaf in a Binary Tree

Given a binary tree where every node has a unique value, and a target key k, find the closest leaf node to target k in the tree.A node is called a leaf if it has no children.In the following examples,...

Do not mess it up 838

Closest Leaf in a Binary Tree

Input: root = [1,2,3,4,null,null,null,5,null,6], k = 2 Diagram of binary tree: 1 / \ 2 3 / 4 / 5 / 6 Output: 3 Expl...

leetcode 解题思路 224

LeetCode解题报告--Remove Element

题目: Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn’t matter what you leave beyond the new length

gannyee 1117

LWC 62:742. Closest Leaf in a Binary Tree

LWC 62:742. Closest Leaf in a Binary Tree传送门:743. 742. Closest Leaf in a Binary TreeProblem: Given a binary tree where every node has a unique value, and a target key k, find the closest leaf node to

Demon-初来驾到 850
上一篇: [Leetcode] 741. Cherry Pickup 解题报告
下一篇: [Leetcode] 743. Network Delay Time 解题报告
魔豆Magicbean
博客等级 码龄19年 146粉丝 742原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值