NeetCode #402LC-250MediumTreesNC Algo100
← Back to All Problems#402 · #250 · Count Univalue Subtrees(统计同值子树)
📌 Problem Statement & Constraints
Given the root of a binary tree, return the number of uni-value subtrees: subtrees in which every node has the same value. Constraints: the number of nodes is in
[0, 1000], -1000 <= Node.val <= 1000.💡 Core Algorithmic Approaches
- A post-order DFS returns whether the subtree rooted at a node is uni-value.
- A node qualifies when both children's subtrees are uni-value and each child's value equals the node's value.
- Count each qualifying node.
- Leaves are always uni-value, which is the natural base case.
💻 Benchmark Python3 Implementation
class Solution:
def countUnivalSubtrees(self, root: Optional[TreeNode]) -> int:
self.cnt = 0
def is_uni(node: Optional[TreeNode]) -> bool:
if not node:
return True # an empty subtree is trivially uni-value
l = is_uni(node.left)
r = is_uni(node.right)
if not (l and r):
return False # a child subtree already failed
if node.left and node.left.val != node.val:
return False
if node.right and node.right.val != node.val:
return False
self.cnt += 1 # this subtree is uni-value
return True
is_uni(root)
return self.cnt⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each node is visited once.
💾 Space Complexity
O(h) for the recursion stack.
⚠️ Interview Pitfalls & Follow-ups
- Counting before verifying the children: a node could be counted even though a descendant differs.
- Comparing only the immediate children's values without their subtree status: both conditions are required.
- Treating an empty subtree as non-uni-value: it must return
Trueso that a single-child node can still qualify. - Using a global counter that is not reset: reset it per call.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Trees Problems
中文速览与面试要点
统计同值子树
给定一个二叉树,统计该二叉树数值 相同 的 子树 个数。同值子树是指该子树的所有节点都拥有相同的数值。约束:二叉树的节点个数在范围 [0, 1000] 内;-1000 ≤ Node.val ≤ 1000。
核心要点
- 后序遍历 + 自底向上判定(标准解) :递归函数返回「以当前节点为根的子树是否所有节点值相同」。
- 判定条件 :左右子树都同值,且左子节点(若存在)的值等于当前值,且右子节点(若存在)的值等于当前值。
- 计数 :满足条件时计数器加一。
- 为什么必须后序 :需要先知道子树的同值性,才能判断当前子树。
常见陷阱
- 先判断「子节点值与当前值相同」再判断子树同值性 :逻辑上等价,但要保证左右子树都同值才计数。
- 空节点返回 False :空节点应视为「同值」(不违反任何约束),否则叶子节点无法计数。
- 忘记 node.left and 的判断 :子节点可能为空,直接访问 node.left.val 会报错。
- 用「统计所有节点的值分布」 :无法判断「子树」范围,必须自底向上。
参考实现
class Solution:
def countUnivalSubtrees(self, root: 'TreeNode') -> int:
cnt = 0
def dfs(node) -> bool:
"""返回以 node 为根的子树是否所有节点值相同。"""
nonlocal cnt
if not node:
return True
l = dfs(node.left)
r = dfs(node.right)
if l and r:
if node.left and node.left.val != node.val:
return False
if node.right and node.right.val != node.val:
return False
cnt += 1 # 当前子树同值
return True
return False
dfs(root)
return cnt