Univalued Binary Tree — LeetCode 965 Python Solution

EasyTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#965
Reading time
3 min

The problem

A binary tree is uni-valued if every node in the tree has the same value. Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.

Example

Input
root = [1,1,1,1,1,null,1]
Output
true

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 isUnivalTree(self, root: Optional[TreeNode]) -> bool:
        def dfs(root: Optional[TreeNode]) -> bool:
            if root is None:
                return True
            return root.val == x and dfs(root.left) and dfs(root.right)

        x = root.val
        return dfs(root)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of nodes in the tree auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 965. Univalued Binary Tree 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 965. Univalued Binary Tree?
LeetCode 965. Univalued Binary Tree is rated Easy on LeetCode.
What is the time complexity of LeetCode 965. Univalued Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 965. Univalued Binary Tree?
The Python solution on this page uses O(n), where n is the number of nodes in the tree auxiliary space.
What topics does LeetCode 965. Univalued Binary Tree cover?
LeetCode 965. Univalued Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview