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

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

这是悦乐书的第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+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

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

Zemax与Matlab交互:双胶合优化详细流程 阅读详情

相关推荐

安川机器人SOCKET 通讯

命令 功能 参数 示例 返回 SelectJob 选择程序 JobName LineNo SelectJob TEST 0 #SelectJob,Ok StartJob 启动程序 JobName StartJob TEST #StartJob,Ok Pause 暂停当前程序 - Pause #Pause,Ok Continue 继续当前程序 - Continue #Continue,Ok ServoOn 伺服上电 - ServoOn #ServoOn,Ok ServoOf...

记录学习内容 8288

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

硬全桥副边钳位管Vds电压凸台揭秘——寄生参数引发的导通异常

本文深入分析了硬全桥副边钳位管Vds电压凸台现象,揭示了寄生参数如何引发导通异常。通过波形分析和工程实践,详细解析了走线电感的蓄能效应和体二极管的接力作用,并提供了PCB布局优化、元件选型和驱动电路调整等解决方案,帮助工程师有效应对这一常见问题。

weixin_30825581的博客 430

Longest Univalue Path问题及解法

687. Longest Univalue Path LeetCode

刘天的博客 1847

树莓派5新手必看:保姆级ibus中文输入法安装与配置全流程(含.bashrc设置避坑)

本文详细介绍了在树莓派5上安装和配置ibus中文输入法的完整流程,包括系统环境准备、ibus框架安装、图形界面配置及常见问题解决方案。通过清晰的步骤说明和避坑指南,帮助新手快速实现中文输入功能,提升开发效率。

weixin_29159441的博客 532

CGAL-5.6的安装与编译(Win10+vs2022+CGAL-5.6+Boost1.82.0)

CGAL是Computational Geometry Algorithms Library(计算几何算法库)的缩写,C++的高效算法库。CGAL只是一个头文件库(从5.0版本开始),这意味着CGAL无需编译,只需安装好CGAL的依赖项即可。CGAL5.6。

baidu_34931359的博客 3903

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的博客 577

用Python实现单层感知器:5分钟搞定逻辑与/或/异或分类(附避坑指南)

本文通过Python代码实战,详细讲解了单层感知器的核心原理与实现步骤,5分钟内即可完成逻辑与、或运算的分类任务。文章深入剖析了单层感知器的能力边界,解释了其无法解决异或(XOR)等线性不可分问题的根本原因,并提供了学习率设置、权重初始化等关键避坑指南,帮助初学者直观理解神经网络的基础。

ttt77的博客 1085

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的博客 64

从零到一:手把手教你用C#开发AGV调度系统(附避坑指南)

本文详细介绍了如何使用C#开发高效的AGV调度系统,涵盖从环境搭建到核心算法实现的完整流程。重点解析了动态路径规划、多机协同等关键技术,并提供了实用的避坑指南和性能优化建议,帮助开发者快速构建工业级车辆控制调度系统。

blockchain9miner的博客 742

激光光束质量评估与光斑尺寸计算:从理论到MATLAB实践

本文详细解析激光光束质量评估与光斑尺寸计算的理论基础及MATLAB实践方法,重点介绍M²因子的测量与应用。通过高斯光束模型、CCD成像法和MATLAB算法实现,帮助读者掌握从理论到实践的完整流程,提升激光系统调试与评估能力。

weixin_29083373的博客 452

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

从零开始深入理解 AI Agent(完整版)

AI Agent(智能体)是一个能够自主感知环境、做出决策、执行行动并记忆经验的智能系统。特性传统程序AI Agent决策方式固定逻辑(if-else)动态推理(LLM 思考)灵活性需要重新编程自然语言描述即可能力边界明确限定可通过工具扩展学习能力无可通过记忆积累经验│ 感知 │ ───→ │ 推理 │ ───→ │ 行动 │↑ │ ││ ↓ ││ 记忆 │ ←─── │ 反思 │ ←─────────┘感知(Perception)

qq_20096229的博客 760

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

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

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

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

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

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

(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的博客 122

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

侠客小虎的博客 762

二叉树之最长同值路径

二叉树之最长同值路径 问题: 思路: 后序遍历 + 递归: 定义变量ans保存最长同值路径长度,初始为0 递归函数的功能为计算从p节点开始,向下出发最长的同值路径长度,递归函数的参数包含引用变量参数ans 先对p节点的左右子树根调用递归函数,得到从左右子树根出发的最长同值路径长度分别为left,right 若左右子树根的值与p节点的值相同,对应的最长同值路径长度 left 或 right 需加...

qq_44709990的博客 388
上一篇: 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、付费专栏及课程。

余额充值