Tensorum
LeetCode 1448 · DFS Basics

Count Good Nodes in Binary Tree

LeetCode 1448 · Medium · solution, intuition & step-by-step walkthrough

Pass the path maximum down.

MediumTreeDepth-First SearchBreadth-First SearchBinary Tree
106 msruntime · beats 98%
69.8 MBmemory · beats 100%
1approach
4accepted runs · last 25 Jun 2024

This is how I solved Count Good Nodes in Binary Tree (LeetCode 1448), a medium problem from the DFS Basics pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

A node is good if no node on the path from the root is larger. Carry the largest value seen on the current path down the recursion and compare.

Approach

  1. 1

    dfs(node, max): None → 0.

  2. 2

    Count 1 if node.val ≥ max.

  3. 3

    Update max and add the counts from both children.

How I solved it

DFS with path maxPythonO(n) time · O(h) space
class Solution:
    def goodNodes(self, root):
        def dfs(node, mx):
            if node is None:
                return 0
            res = 1 if node.val >= mx else 0
            mx = max(node.val, mx)
            res += dfs(node.left, mx)
            res += dfs(node.right, mx)
            return res
        return dfs(root, float("-inf"))
Loading the step-through…

Count Good Nodes in Binary Tree — FAQ

What is the intuition behind Count Good Nodes in Binary Tree?

A node is good if no node on the path from the root is larger. Carry the largest value seen on the current path down the recursion and compare.

How do you solve Count Good Nodes in Binary Tree (LeetCode 1448)?

1. dfs(node, max): None → 0. 2. Count 1 if node.val ≥ max. 3. Update max and add the counts from both children.

What is the time and space complexity of Count Good Nodes in Binary Tree?

Time: O(n). Space: O(h). (Accepted approach: DFS with path max.)

What are common mistakes in Count Good Nodes in Binary Tree?

Use ≥ — equal values count as good.