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