# 687 Longest Univalue Path

### 687. Longest Univalue Path

Easy

##### 很重要的一点就是，Note: The length of path between two nodes is represented by the number of edges between them.
• 因此是self.res = max(self.res, left_arrow + right_arrow), return max(left_arrow, right_arrow)
• 而不是self.res = max(self.res, left_arrow + right_arrow + 1), return max(left_arrow + 1, right_arrow + 1)
# 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
"""
self.res = 0
def dir_length(node):
if not node:
return 0
left_len = dir_length(node.left)     # 左节点的length
right_len = dir_length(node.right)   # 右节点的length
left_dir, right_dir = 0, 0
if node.left and node.left.val == node.val:
left_dir = left_len + 1          # 当前节点的左节点方向的length
if node.right and node.right.val == node.val:
right_dir = right_len + 1        # 当前节点的右边节点方向的length
self.res = max(self.res, left_dir + right_dir)
return max(left_dir, right_dir)
dir_length(root)
return self.res