NeetCode #441LC-1448MediumTreesNC 150NC 250
← Back to All Problems#441 · #1448 · Count Good Nodes in Binary Tree(统计二叉树中好节点的数目)
📌 Problem Statement & Constraints
Given a binary tree, a node
X is good if, on the path from the root to X, there is no node with a value greater than X.val. Return the number of good nodes. Constraints: the number of nodes is in [1, 10^5], -10^4 <= Node.val <= 10^4.💡 Core Algorithmic Approaches
- Do a DFS carrying the maximum value seen along the path.
- At each node, if
node.val >= max_so_far, the node is good. - Then recurse with
max(max_so_far, node.val). - The root is always good, since the initial maximum is
-infinity.
💻 Benchmark Python3 Implementation
class Solution:
def goodNodes(self, root: TreeNode) -> int:
def dfs(node: Optional[TreeNode], mx: int) -> int:
if not node:
return 0
cnt = 1 if node.val >= mx else 0 # good if no greater ancestor
mx = max(mx, node.val) # update for the children
return cnt + dfs(node.left, mx) + dfs(node.right, mx)
return dfs(root, float("-inf"))⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): every node is visited once.
💾 Space Complexity
O(h) for the recursion stack.
⚠️ Interview Pitfalls & Follow-ups
- Using
>instead of>=: a node equal to the path maximum is still good. - Initialising the maximum to 0: negative values are allowed, so
-infinityis required, otherwise negative nodes would be wrongly rejected. - Comparing against the immediate parent instead of the path maximum: the condition is about the whole path.
- Not updating the maximum before recursing: the children would see the stale value.
⚡
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
中文速览与面试要点
统计二叉树中好节点的数目
给你一棵根为 root 的二叉树,请你返回二叉树中好节点的数目。「好节点」X 定义为:从根到该节点 X 所经过的节点中, 没有任何节点的值大于 X 的值 。约束:二叉树中节点数目范围是 [1, 10^5];每个节点权值的范围是 [-10^4, 10^4]。
核心要点
- 前序遍历 + 路径最大值(标准解) :递归时携带「从根到当前节点路径上的最大值」,若当前节点值 ≥ 该最大值,则它是好节点。
- 更新最大值 : mx = max(mx, node.val) ,传给左右子树。
- 初始值 :根节点的路径最大值应设为 −∞,这样根节点必然是好节点。
- 复杂度 :O(n) 时间、O(h) 空间。
常见陷阱
- 初始最大值设为 0 :节点值可能全为负数,用 0 会让所有节点都不是好节点。必须用 −∞。
- 比较用 > 而非 >= :题目要求「没有任何节点的值 大于 X」,因此等于路径最大值时 X 仍是好节点,应用 >= 。
- 忘记把更新后的最大值传给子节点 :会导致路径信息丢失。
- 递归深度过大 :n 可达 10^5,链状树会栈溢出,需 sys.setrecursionlimit 或改迭代。
参考实现
class Solution:
def goodNodes(self, root: 'TreeNode') -> int:
def dfs(node, mx: int) -> int:
if not node:
return 0
cnt = 1 if node.val >= mx else 0 # 当前节点是好节点?
new_mx = max(mx, node.val)
return cnt + dfs(node.left, new_mx) + dfs(node.right, new_mx)
return dfs(root, float('-inf'))