[一起来刷leetcode吧][23]--No.687 Longest Univalue Path

这篇文章是程序自动发表的,详情可以见 这里
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">

这是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 represented by the number of edges between them. example:output 3

              4
             / \
            4   4
           / \   \
          4   4   5

  思路 将左右汇聚到根节点再进行比较即可,为了能使代码更简洁,我把None的值赋为root.val-1.注意是求路径,而不是边数最多的子树,要求后者,只需将最后一行代码改为return r l 2   

show me the code

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def longestUnivaluePath(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:return 0
        self.mx = 0
        self.find(root)
        return self.mx
    def find(self,root):
        if not root.left and not root.right:return 0
        if root.left:
            lval = root.left.val
            l = self.find(root.left) 
        else:
            lval = root.val-1
            l = 0
        if root.right:
            r = self.find(root.right)
            rval = root.right.val            
        else:
            rval = root.val-1
            r = 0
        if root.val != lval and root.val!=rval:
            self.mx = max(self.mx,l,r)
            print '00'
            return 0
        elif  root.val == lval and root.val!=rval:
            self.mx = max(self.mx,l 1,r)
            print '10'
            return l 1
        elif  root.val != lval and root.val==rval:
            self.mx = max(self.mx,l,1 r)
            print '01'
            return r 1
        else:
            print '11'
            self.mx = max(self.mx,l 2 r)
            return max(l,r) 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值