-
Notifications
You must be signed in to change notification settings - Fork 171
/
687.py
24 lines (23 loc) · 796 Bytes
/
687.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 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
"""
longest = [0]
def traverse(node):
if not node:
return 0
left_len, right_len = traverse(node.left), traverse(node.right)
left = (left_len + 1) if node.left and node.left.val == node.val else 0
right = (right_len + 1) if node.right and node.right.val == node.val else 0
longest[0] = max(longest[0], left + right)
return max(left, right)
traverse(root)
return longest[0]