Python 0965.py
class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
def deeper(node):
if not node:
return True
if node.val != root.val:
return False
return deeper(node.left) and deeper(node.right)
return deeper(root)
Difficulty
and has an acceptance rate of about 73% (300k+ submissions).
Typical patterns to solve this problem:
- Binary Tree
- Breadth First Search
- 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 provided implementation defines a method isUnivalTree that determines whether every node in a binary tree shares the same value as the root. The algorithm relies on a nested helper function that walks the tree recursively, comparing each visited node to the root’s value and propagating a boolean result upward.
Core Logic
Method Signature
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
The public entry point receives the tree’s root and returns a single boolean indicating uniformity.
Recursive Helper
def deeper(node):
if not node:
return True
if node.val != root.val:
return False
return deeper(node.left) and deeper(node.right)
The helper deeper embodies the traversal:
- The first conditional treats a missing node as trivially satisfying the uniformity condition, allowing the recursion to terminate cleanly at leaf boundaries.
- The second conditional checks the current node’s value against the root’s value. A mismatch triggers an immediate
Falsereturn, preventing further descent. - The final line combines the results of the left and right sub-trees using logical
and, which short-circuits if either side yieldsFalse.
Invocation
return deeper(root)
The outer method simply launches the recursion from the root node.
Edge Cases Handled
When the input tree is empty (root is None), the helper receives None on its first call. The base case if not node: return True treats this as a valid unival tree, returning True without further processing.
A tree consisting of a single node also satisfies the condition. The helper evaluates the node, finds its value equal to root.val, and then recurses on both children, which are None. Both recursive calls hit the base case and return True, yielding an overall True.
If any node in the structure holds a value different from the root’s value, the second conditional detects the discrepancy instantly. The function returns False at that point, and the logical and in the caller prevents any deeper exploration of that branch.
Performance Optimizations
The algorithm benefits from early termination. As soon as a mismatched value is encountered, the function returns False without traversing the remaining subtree. This behavior leverages Python’s short-circuit evaluation in the expression deeper(node.left) and deeper(node.right), ensuring that the right-hand side is not evaluated when the left side already yields False.
Capturing root.val from the enclosing scope eliminates the need to pass the reference value through recursive parameters, reducing call-frame overhead. The nested helper also avoids repeated attribute lookups on the outer self object, keeping the inner loop tight.
Overall, the design provides a concise depth-first traversal that stops at the first sign of non-uniformity, minimizing unnecessary work while maintaining clear readability.
ELI5 - Simplified Explanation
Imagine a tree made of numbers where every leaf and branch has a secret value written on it. The goal is to check if every single spot in the whole tree has the exact same number as the very first one at the top.
To do this, a helper explorer starts at the top of the tree and remembers the number it sees there. Then, the explorer travels down every single path to visit every spot. At each place, it stops to check if the number written there matches the starting number. If it finds even one number that is different, it knows the tree is not special. If it makes it through every single path and sees that every spot has the same number as the top, then the tree is a perfect match.
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++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 563: Binary Tree Tilt
- problem 938: Range Sum of BST
- problem 146: LRU Cache
- problem 371: Sum of Two Integers
- problem 865: Smallest Subtree with all the Deepest Nodes
- problem 1201: Ugly Number III
- problem 2707: Extra Characters in a String
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