Longest Univalue Path — LeetCode 687 Python Solution
MediumTreeDepth-First SearchBinary Tree
- Problem
- #687
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
Example
- 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).
Python solution
Python
# 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 longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
l, r = dfs(root.left), dfs(root.right)
l = l + 1 if root.left and root.left.val == root.val else 0
r = r + 1 if root.right and root.right.val == root.val else 0
nonlocal ans
ans = max(ans, l + r)
return max(l, r)
ans = 0
dfs(root)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 687. Longest Univalue Path is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 687. Longest Univalue Path?
- LeetCode 687. Longest Univalue Path is rated Medium on LeetCode.
- What is the time complexity of LeetCode 687. Longest Univalue Path?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 687. Longest Univalue Path?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 687. Longest Univalue Path cover?
- LeetCode 687. Longest Univalue Path is tagged Tree, Depth-First Search and Binary Tree on LeetCode.