LeetCode算法题-Longest Univalue Path(Java实现)

二叉树常见算法总结(一) 一、在二叉树中,找到距离最远的两个节点的距离 在二叉树中,找到距离最远的两个节点的距离。在上面的二叉树中,最远的节点的距离是:4(路径是2-3-13-5-2)。 解决思路:遍历每个节点,找出以当前节点为根的最长路径,然后找出所有最长路径中的最大值。思路类似于最大路径和。 下面直接给出代码。 void longestPathUtil(Node* root, int& le 阅读详情

这是悦乐书的第290次更新,第308篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第158题(顺位题号是687)。给定二叉树,找到路径中每个节点具有相同值的最长路径的长度。此路径可能会也可能不会通过根目录。例如:

输入:

              5
             / \
            4   5
           / \   \
          1   1   5

输出:路径为[5,5,5],边长为2


输入:

              1
             / \
            4   5
           / \   \
          4   4   5

输出:路径为[4,4,4],边长为2


注意:

  • 两个节点之间的路径长度由它们之间的边数表示。

  • 给定的二叉树不超过10000个节点。 树的高度不超过1000。

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

此题与求二叉树的最长路径边长相似,只是此题要求是节点值相同的路径,也就是说在找最长路径的时候,还需要判断节点值,要是不相同,就重置为0,在此期间,我们使用一个全局变量来存储最长节点值相同路径的边长。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int count = 0;
    public int longestUnivaluePath(TreeNode root) {
        helper(root);
        return count;
    }

    public int helper(TreeNode node){
        if (node == null) {
            return 0;
        }
        int left = helper(node.left);
        int right = helper(node.right);
        if (node.left == null || node.left.val != node.val) {
            left = 0;
        }
        if (node.right == null || node.right.val != node.val) {
            right = 0;
        }
        count = Math.max(count, left+right);
        return Math.max(left, right)+1;
    }
}

03 第二种解法

如果你对上面的解法不太理解,尤其是递归方法最后一步返回left与right中的最大值再加1,可以看看此种解法。在处理完左子树的节点后,如果当前节点和其左子节点的节点值相等,那么left就在原基础上加1,否则就重置为0。因为要想最长,从当前节点开始,就是其左右子树中的最长相同节点值路径加上当前节点本身。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    int count = 0;
    public int longestUnivaluePath(TreeNode root) {
        helper(root);
        return count;
    }

    public int helper(TreeNode node){
        if (node == null) {
            return 0;
        }
        int left = helper(node.left);
        int right = helper(node.right);
        left = node.left != null && node.left.val == node.val ? left+1 : 0;
        right = node.right != null && node.right.val == node.val ? right+1 : 0;
        count = Math.max(count, left+right);
        return Math.max(left, right);
    }
}

04 小结

算法专题目前已日更超过四个月,算法题文章158+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: NO)解决办法 问题:ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: NO) 很久没用这台电脑的mysql了,今天需要连接数据库,启动数据库报错: ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: NO) 解决方法: 查阅资料后知道了,应该使用已知的用户名和密码登陆 mysql -u root -p 然而密 阅读详情

相关推荐

手把手教你用YOLOv11-seg-LSCD搞定树脂件瑕疵检测(附数据集与代码)

本文详细介绍了如何使用YOLOv11-seg-LSCD模型进行工业级树脂件瑕疵检测,包括环境配置、数据集构建、模型训练与调优、部署优化等全流程。通过LSCD模块的创新设计,有效提升了气泡、裂纹等微小缺陷的检测精度,适用于各类树脂制品的质量检测场景。

weixin_28677005的博客 425

Longest Univalue Path问题及解法

687. Longest Univalue Path LeetCode

刘天的博客 1847

主流仿真软件Sigrity/HFSS/Siwave/Hyperlynx/ADS差异

在电子设计自动化(EDA)领域,各种仿真软件如Cadence Sigrity、Mentor Graphics的HyperLynx、Keysight的ADS以及ANSYS的SIwave等,都广泛应用于不同的应用场景中。综上所述,这些EDA仿真软件在各自的应用场景中发挥着重要作用,帮助工程师在设计阶段就能够评估和优化电子产品的性能,提高设计的可靠性和效率。:Sigrity由全球最大的EDA公司Cadence推出,Cadence还推出了Orcad和Allegro等著名软件。:由安捷伦(现是德科技)公司开发。

Geektec的专栏 9424

Longest Univalue Path

题目链接:https://leetcode.com/problems/longest-univalue-path/ 这道题没有做出来,伤心。其实就差那么一点了,最终还是没有……,特此纪念这道题。# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # s

LiuY_ang的博客 578

保姆级教程:手把手教你用RKISP TURN为RV1106生成和配置IQfile(附AIQ版本匹配避坑指南)

本文提供RV1106 ISP调试的完整指南,详细讲解如何使用RKISP TURN工具生成和配置IQfile,包括环境搭建、参数调试、设备树配置及常见问题解决方案。特别强调AIQ版本匹配的重要性,帮助开发者避免常见陷阱,提升图像信号处理效率。

weixin_42520796的博客 507

隧道裂缝检测【C++PCL】

我们团队注重每一个细节,确保代码的可读性、可维护性和可扩展性达到最高标准。我们严格遵循行业最佳实践,采用模块化和面向对象的设计原则,使得我们的代码结构清晰且易于理解。我们的点云服务更是引以为傲。我们的技术团队拥有深厚的专业知识和丰富的经验,能够提供高度准确和高效的点云处理服务。无论是点云的获取、存储还是分析,我们都能够满足客户的需求,并提供出色的解决方案。我们的技术实力也是无与伦比的,拥有广泛的技术背景和深入的专业知识。

weixin_45196569的博客 853

Longest Univalue Path——LeetCode进阶路

原题链接https://leetcode.com/problems/longest-univalue-path 题目描述 Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass th...

Moliay的博客 313

世界模型研究综述【20250702】

自2018年以来,世界模型研究从早期的生成式环境模型+简单控制器,发展到如今与大模型和多模态深度融合,取得了长足进展。Ha和Schmidhuber开创了让智能体“在梦中学习”的范式,随后模型式强化学习在复杂视觉任务中展现威力,如SimPLe和PlaNet将世界模型引入Atari和连续控制。Dreamer系列通过潜在空间想象将这一思路推向极致,从连续控制拓展到Atari甚至开放式3D游戏,实现了统一算法征服多领域任务的壮举。

u013250861的博客 540

LeetCode 687. Longest Univalue Path

原题链接在这里:https://leetcode.com/problems/longest-univalue-path/ 题目: Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pas...

weixin_30699443的博客 65

知识蒸馏⚗️ | YOLOv5知识蒸馏实战篇

YOLOv5知识蒸馏教程

Coding... 9367

【毕设实战】基于YOLOv8的HRSC2016船舶智能检测系统开发全指南(含可视化UI界面,打造海事领域高分毕设)

亲爱的同学,通过这篇教程,你已经掌握了“基于YOLOv8的HRSC2016微小船只检测系统”从数据集处理、模型训练到Tkinter界面开发的全流程。这个课题既贴合“海事智能化”的产业战略,又涵盖了“目标检测、深度学习、界面开发”等多个毕设评分点,非常适合作为计算机或海事工程专业的毕业设计。在实践中,你可能会遇到“海面背景复杂导致船只漏检”“微小船只识别精度不足”“UI与模型推理同步卡顿”等挑战——别担心,这些都是技术成长的必经之路。

know_F0727的博客 134

leetcode 687 Longest Univalue Path

Java:class Solution { public int longestUnivaluePath(TreeNode root) { int[] res=new int[1]; if(root != null) dfs(root,res); return res[0]; } private int dfs(Tr

MRxjh的博客 648

Python爬虫实战:实时监控美国SEC官网文件更新,助你第一时间掌握市场动态

在资本市场中,信息就是财富。美国证券交易委员会(SEC)官网公开了大量公司披露文件,涵盖财报、招股说明书、内幕交易等重要信息。对投资者、分析师及法律合规人员来说,实时监控这些公开文件具有重要价值。

2201_76125261的博客 600

LeetCode 687. Longest Univalue Path(java)

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.Note: The length of path between two nodes is rep

katrina95的博客 482

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

leetcode_687. Longest Univalue Path ? 待解决

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.Note: The length of path between two nodes is rep

wjheha的博客 314

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LeetCode687. Longest Univalue Path

687.Longest Univalue Path题意:Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. 给定一棵二叉树,寻找符合条件的最长路

YTTmiao的博客 389

ssm框架搭建

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

(Java)leetcode-687 Longest Univalue Path (最长同值路径)

后序遍历,自下而上

不思量 192

leetcode 687. Longest Univalue Path 二叉树最长相等路径+ 深度优先遍历DFS

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. Note: The length of path between two nodes is ...

JackZhangNJU的专栏 556

[LeetCode] 687. Longest Univalue Path 最长唯一值路径

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. Note:The length of path between two nodes is ...

weixin_30826095的博客 131

java最长同值路径_LeetCode 687. Longest Univalue Path 最长同值路径 (C++/Java)

题目:Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.The length of path between two nodes is repre...

weixin_39906521的博客 123

leetcode 687. 最长同值路径(Longest Univalue Path)

给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。 注意:两个节点之间的路径长度由它们之间的边数表示。 示例 1: 输入: 5 / \ 4 5 / \ \ 1 1 5 输出: 2 示例 2:...

一叶之修的博客 366

LeetCode.687 Longest Univalue Path (经典的求相同节点最长路径)

题目: Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. Note: The length of path between tw

侠客小虎的博客 763

暴力法求二叉树内最大路径长度

原理很简单,二叉树内最大的路径的起点和终点一定是叶子。据此可以遍历所有的叶子进行暴力求解(好好的分治法能解决的问题被我弄成这样) 二叉树的节点定义如下: package cn.edu.nju.zyf.longestPathWithinABinaryTree; public class Node { private String data; public Node parent;

zhuyuanfu的专栏 650
上一篇: LeetCode算法题-Repeated String Match(Java实现)
下一篇: LeetCode算法题-Employee Importance(Java实现)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址