Python 0687.py
class Solution:
def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
result = 0
def deeper(node, value):
if not node:
return 0
l = deeper(node.left, node.val)
r = deeper(node.right, node.val)
godown = 0
nonlocal result
if value == node.val:
# continue down
length = 1 + max(l, r)
result = max(result, length)
godown = length
# new path, connecting left and right
length = 1 + l + r
result = max(result, length)
return godown
deeper(root, float("inf"))
return max(result - 1, 0)
Difficulty
and has an acceptance rate of about 44% (500k+ submissions).
Typical patterns to solve this problem:
- Binary Tree
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation defines a class Solution with a method longestUnivaluePath that computes the length of the longest path in a binary tree where every node on the path shares the same value. The method receives the root of the tree and returns an integer representing the number of edges on that maximal univalue path. The algorithm performs a depth-first traversal, accumulating candidate path lengths while maintaining a global result that records the best value seen so far.
Core Logic
The entry point initializes a mutable result variable to zero and defines a nested helper function deeper. The helper receives a node and the value that the current branch is expected to match. It returns the length of the longest downward continuation that can be attached to the parent node.
def deeper(node, value):
if not node:
return 0
The base case returns zero for a null child, ensuring that leaf nodes contribute no further length.
The recursive calls explore both subtrees, passing the current node’s value as the expected value for the children. This captures the requirement that a child can only extend the univalue path if it matches its parent.
l = deeper(node.left, node.val)
r = deeper(node.right, node.val)
A local variable godown is prepared to hold the length that can be propagated upward. The nonlocal declaration allows the helper to update the outer result variable without returning it.
godown = 0
nonlocal result
When the incoming value matches the node’s own value, the algorithm can extend a path upward. It selects the larger of the left or right continuation, adds one for the current edge, updates the global maximum, and stores the length in godown.
if value == node.val:
length = 1 + max(l, r)
result = max(result, length)
godown = length
Regardless of the match, the code also evaluates a path that connects the left and right branches through the current node. This “new path” uses both left and right continuations plus the current node, and it updates the global result accordingly.
length = 1 + l + r
result = max(result, length)
Finally, the helper returns the downward-extendable length, which may be zero if the node does not match the expected value.
return godown
The outer call starts the recursion with a sentinel value (float("inf")) that will never equal the root’s value, forcing the algorithm to treat the root as the start of a new path.
deeper(root, float("inf"))
The method concludes by converting the node count stored in result to an edge count, ensuring that a single node yields zero edges.
return max(result - 1, 0)
Edge Cases Handled
The recursion’s early return for a None node gracefully handles an empty tree, resulting in a final answer of zero. When the tree consists of a single node, the sentinel value prevents any upward extension, and the final subtraction yields zero edges, which is the correct output. Trees where all nodes share the same value trigger the branch where value == node.val at every level, allowing the algorithm to accumulate the full depth of the tree as a candidate path. Conversely, trees with alternating values cause the godown variable to remain zero for mismatched nodes, while still evaluating the “new path” that joins left and right sub-paths, ensuring that isolated univalue segments are considered. Deeply unbalanced trees are processed without special casing because the recursion naturally follows the existing structure, and the base case prevents stack overflow beyond Python’s recursion limits for typical input sizes.
Performance Optimizations
The design consolidates all necessary information into a single traversal. By updating a shared result variable inside the recursive function, the algorithm avoids the overhead of returning multiple values or constructing auxiliary data structures. The use of max(l, r) when extending upward ensures that only the longer branch contributes to the parent’s potential path, minimizing unnecessary calculations. The separate evaluation of the combined left-right path (1 + l + r) captures the longest possible path that passes through the current node without requiring a second pass. The sentinel value passed to the initial call eliminates the need for a special case for the root, streamlining the control flow. Overall, the approach leverages recursion to achieve a concise, in-place computation that scales linearly with the number of nodes.
ELI5 - Simplified Explanation
Imagine a tall tree made of branches where every branch has a colorful sticker on it. Some stickers are red, some are blue, and some are green. The goal is to find the longest path through the tree where every single sticker is the exact same color. To do this, the code starts at the very top of the tree and looks at each branch one by one. It travels down to the left and the right to see what colors are hiding there.
When the code visits a branch, it asks a simple question. Does this branch have the same color as the one above it? If the answer is yes, then the path keeps growing longer because the color stays the same. If the answer is no, the path has to stop and start fresh. As the code wanders through all the branches, it keeps a secret note of the longest path it has found so far. Once it has looked at every single branch from top to bottom, it checks its note to tell everyone how many matching stickers it found in a row.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | JS | Rust | C | Go | TS | |||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| haoel | Python | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| haoel | Python | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 124: Binary Tree Maximum Path Sum
- problem 2246: Longest Path With Different Adjacent Characters
Solved On The Same Day
- problem 292: Nim Game
- problem 572: Subtree of Another Tree
- problem 617: Merge Two Binary Trees
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 213: House Robber II
- problem 237: Delete Node in a Linked List
- problem 260: Single Number III
- problem 416: Partition Equal Subset Sum
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 560: Subarray Sum Equals K
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 655: Print Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 669: Trim a Binary Search Tree
- problem 1115: Print FooBar Alternately
- problem 1116: Print Zero Even Odd
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality