PracticeNeetCode ↗LeetCode ↗
Given a binary tree, a node is "good" if no node on the path from the root down to it has a greater value. Return the total number of good nodes.
Time: O(n) — Space: O(h)
def goodNodes(root: TreeNode) -> int:
def dfs(node: TreeNode | None, max_so_far: int) -> int:
if not node:
return 0
count = 1 if node.val >= max_so_far else 0
new_max = max(max_so_far, node.val)
count += dfs(node.left, new_max) + dfs(node.right, new_max)
return count
return dfs(root, root.val)How the solution above works, piece by piece.
dfs(node, max_so_far) carries the largest value seen on the path from the root down to this node.count = 1 if node.val >= max_so_far: nothing above is bigger, so the node is good. Equal counts as good.new_max includes this node before going deeper.max_so_far = root.val so the root counts. O(n) time, O(height) stack.Running it on root = [3, 1, 4, 3, null, 1, 5]:
max_so_far, the biggest value above it (shown under the node). It's good if its value is at least that. The left 1 (max 3) and the lower 1 (max 4) are not good; 3, 4, the lower 3 and 5 are.