LeetCode 687. 最长同值路径

目录结构

1.题目

2.题解


1.题目

给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。

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

示例:

输入:

              5
             / \
            4   5
           / \   \
          1   1   5
输出:

2


输入:

              1
             / \
            4   5
           / \   \
          4   4   5
输出:

2

注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。 

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

2.题解

public class Solution687 {

    @Test
    public void test687() {
        TreeNode root = new TreeNode(1, new TreeNode(4, new TreeNode(4), new TreeNode(4)),
                new TreeNode(5, null, new TreeNode(5)));
        System.out.println(longestUnivaluePath(root));
    }

    int result;

    public int longestUnivaluePath(TreeNode root) {
        result = 0;
        getLongestUnivaluePath(root);
        return result;
    }

    public int getLongestUnivaluePath(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int left = getLongestUnivaluePath(node.left);
        int right = getLongestUnivaluePath(node.right);
        int currentLeft = 0, currentRight = 0;
        if (node.left != null && node.left.val == node.val) {
            currentLeft += left + 1;
        }
        if (node.right != null && node.right.val == node.val) {
            currentRight += right + 1;
        }
        result = Math.max(result, currentLeft + currentRight);
        return Math.max(currentLeft, currentRight);
    }
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(h)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值