MediumNo. 0250LeetCode Premium
Count Univalue Subtrees — LeetCode 250 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Binary Tree
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a binary tree, return the number of uni-value subtrees. A uni-value subtree means all nodes of the subtree have the same value.
Example
- Input
- root = [5,1,5,5,5,null,5]
- Output
- 4
Python solution
# 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 countUnivalSubtrees(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if root is None:
return True
l, r = dfs(root.left), dfs(root.right)
if not l or not r:
return False
a = root.val if root.left is None else root.left.val
b = root.val if root.right is None else root.right.val
if a == b == root.val:
nonlocal ans
ans += 1
return True
return False
ans = 0
dfs(root)
return ansComplexity
- Time
- O(V+E)
- Space · auxiliary
- O(V)
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 250. Count Univalue Subtrees 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
| No. | Problem | Difficulty |
|---|---|---|
| 0098 | Validate Binary Search Tree | Medium |
| 0099 | Recover Binary Search Tree | Medium |
| 0100 | Same Tree | Easy |
| 0101 | Symmetric Tree | Easy |
| 0104 | Maximum Depth of Binary Tree | Easy |
| 0110 | Balanced Binary Tree | Easy |
Frequently asked questions
- How hard is LeetCode 250. Count Univalue Subtrees?
LeetCode 250. Count Univalue Subtrees is rated Medium on LeetCode.
- What is the time complexity of LeetCode 250. Count Univalue Subtrees?
The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 250. Count Univalue Subtrees?
The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 250. Count Univalue Subtrees cover?
LeetCode 250. Count Univalue Subtrees is tagged Tree, Depth-First Search and Binary Tree on LeetCode.
- Is LeetCode 250. Count Univalue Subtrees a premium problem?
Yes. LeetCode 250. Count Univalue Subtrees is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.