Problem 965

Abstract / Summary

Check if every node in a binary tree has the same value

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
10 lines | 322 bytes | submitted September 2, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 False return, 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 yields False.

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.31 | σ = 0.77

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
33 links | 19 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 easy 5 medium
8 solutions   September 2, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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