[leetcode]687. Longest Univalue Path(Python)

[leetcode]687. Longest Univalue Path

题目描述

Category:Easy Tree

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 represented by the number of edges between them.
在这里插入图片描述在这里插入图片描述

题目理解

给定一棵二叉树,查找每个节点具有相同值的最长路径的长度。两个节点之间的路径长度由他们之间的边数来表示。

解题思路

DFS

采用DFS的思想,求一个顶点到所有根节点的路径,时刻保留相等元素的最大值。相等元素的最大值是左右子树的相等元素的最大值+1。
定义的DFS函数是获得在通过root节点的情况下,最长单臂路径。其中更新的res是左右臂都算上的。所以这个题和普通的题是有点不一样。
思路学习:https://blog.csdn.net/fuxuemingzhu/article/details/79248926#DFS_53

class Solution:
	# Runtime: 448ms 38.64%  MemoryUsage: 16MB 100.00%
    def longestUnivaluePath(self, root: TreeNode) -> int:
        if not root:
            return 0
        self.res = 0
        self.getPath(root)
        return self.res

    def getPath(self, root):
        if not root:
            return 0
        left = self.getPath(root.left)
        right = self.getPath(root.right)
        pl, pr = 0, 0
        if root.left and root.left.val == root.val:
            pl = 1 + left
        if root.right and root.right.val == root.val:
            pr = 1 + right
        self.res = max(self.res, pl + pr)
        return max(pl, pr)

用self.res记录过程中可能出现的连通路径(最大值路径),但往上一层返回的仅是左右子节点中的最大值,厉害哦!我就差了这一点!

MyMethod

有点问题的我的代码,失败testcase:[1,null,1,1,1,1,1,1]

class Solution:
	def longestUnivaluePath(self, root: TreeNode) -> int:
        if root is None:
            return 0
        if not root.left and not root.right:
            return 0
        left = self.longestUnivaluePath(root.left)
        right = self.longestUnivaluePath(root.right)
        if root.left and root.left.val == root.val:
            left += 1
        if root.right and root.right.val == root.val:
            right += 1
        if root.right and root.left and root.right.val == root.left.val and root.left.val == root.val:
            return right + left
        else:
            return max(right, left)

Time

2020.3.23 测试用例教我成长!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值