Count Univalue Subtrees — LeetCode 250 Python Solution
MediumLeetCode PremiumTreeDepth-First SearchBinary Tree
- Problem
- #250
- Pattern
- Tree Traversal
- 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
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 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
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
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
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.