687. Longest Univalue Path

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

Constraints:

The number of nodes in the tree is in the range [0, 104].
-1000 <= Node.val <= 1000
The depth of the tree will not exceed 1000.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-univalue-path
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

递归调用,递归函数返回的不是子节点的最长路径值,而是子节点能连上当前根节点的最大长度,即要么是他的左子树要么是他的右子树,取最大的那个,这样子才能街上根节点。

class Solution {
    int ans = 0;
    public int longestUnivaluePath(TreeNode root) {
        if (root == null) {
            return 0;
        }
        check(root);
        return ans;
    }

    private int check(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = check(root.left);
        int right = check(root.right);
        
        
        // 如果当前节点和左子节点一样,那么就可以把左边的数量和当前根节点的1个拼上来,left++
        if (root.left != null && root.val == root.left.val) {
            left++;
        } else {
            left = 0;
        }

        if (root.right != null && root.val == root.right.val) {
            right++;
        } else {
            right = 0;
        }
        ans = Math.max(ans, left + right);
        return Math.max(left, right);
    }
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值