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

本文介绍了一种算法,用于寻找二叉树中有相同值的最长路径。该路径可能穿过根节点也可能不穿过。通过递归地比较左右子树的值来确定路径长度,并更新最长路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given the root of a binary tree, return 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 the path between two nodes is represented by the number of edges between them.

Example 1:
在这里插入图片描述
Input: root = [5,4,5,1,1,5]
Output: 2

Example 2:
在这里插入图片描述
Input: root = [1,4,5,4,4,5]
Output: 2

给出一棵二叉树,找出其中有相同值的最长路径,这个路径可以不通过root

思路:
观察Example2可以发现不通过root时,结果可用左右路径长相加。
而观察Example1可发现通过root时,结果只能取左右路径中较长的一个。
所以需要一个函数,用左右路径相加更新结果,同时要返回左右路径中较长的一个。

而只有root.val和左右子树root.val相等时,路径长才有1+递归下一个左右子树,直到root==null,路径长返回0

class Solution {
    int result = 0;
    public int longestUnivaluePath(TreeNode root) {
        if(root == null) return 0;
        helper(root);
        return result;
    }
    
    int helper(TreeNode root) {
        if(root == null) return 0;
        int left = helper(root.left);
        int right = helper(root.right);
        int leftLen = 0;
        int rightLen = 0;
        if(root.left != null && root.left.val == root.val) {
            leftLen = 1 + left;
        }
        if(root.right != null && root.right.val == root.val) {
            rightLen = 1 + right;
        }
        result = Math.max(result, leftLen + rightLen);
        return Math.max(leftLen, rightLen);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值