Medium
,Tree
,DFS
Given the root of a binary tree, return 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 the path between two nodes is represented by the number of edges between them.
Input: root = [5,4,5,1,1,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 5).
Input: root = [1,4,5,4,4,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 4).
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.mx = 0
def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
if not root: return 0
def dfs(root: Optional[TreeNode], num: int) -> int:
if not root: return 0
l = dfs(root.left, root.val)
r = dfs(root.right, root.val)
self.mx = l + r if l + r > self.mx else self.mx
return 0 if root.val != num else 1 + max(l, r)
dfs(root, root.val)
return self.mx
Kobe BryantNov 25, 2022