Want Help Cracking FAANG?

(Then click this)

×
Back to Main Page

1448. Count Good Nodes in Binary Tree - Leetcode Solution


💡 Step-by-Step Thought Process

Solution Explanation

The problem asks to count the number of "good" nodes in a binary tree, where a node is good if its value is greater than or equal to the maximum value on the path from the root to that node.

The solution uses an iterative depth-first search (DFS) with a stack to traverse the tree and track the maximum value along each path. Here’s how it works:

  • Initialization: We initialize a counter good_nodes to 0 and a stack with the root node and an initial maximum value of negative infinity (to ensure the root is always good).
  • Iterative Traversal: While the stack is not empty, pop a node and its associated maximum value (largest):
    • If the node’s value is at least largest, increment good_nodes, as the node is good.
    • Update largest to the maximum of the current largest and the node’s value, as this is the new maximum for the path to the node’s children.
    • Push the right and left children (if they exist) onto the stack, along with the updated largest.
  • Result: Return good_nodes, the total count of good nodes.
  • Why This Works: The stack-based DFS ensures we visit each node exactly once, and by passing the maximum value seen along the path to each node, we can determine if the node is good by comparing its value to this maximum. The initial negative infinity ensures the root node is always counted, and updating the maximum at each step correctly tracks the path’s maximum for child nodes.
  • Time and Space Complexity: The solution visits each node once, so the time complexity is O(n), where n is the number of nodes. The stack stores at most O(h) nodes, where h is the tree’s height, which is O(n) in the worst case (e.g., a skewed tree), so the space complexity is O(n).

Code Solution

class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        good_nodes = 0
        stk = [(root, float("-inf"))]

        while stk:
            node, largest = stk.pop()
            
            if largest <= node.val:
                good_nodes += 1

            largest = max(largest, node.val)
            if node.right: stk.append((node.right, largest))
            if node.left: stk.append((node.left, largest))

        return good_nodes

# Time Complexity: O(n)
# Space Complexity: O(n)

                

                

                

                

Detailed Explanation

Get Personalized Support at AlgoMap Bootcamp 💡