Hide sidebar

Count Good Nodes in Binary Tree

TreesDFS
MediumLeetCode #1448
20 min

Problem Statement

Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X. Return the number of good nodes in the binary tree.

Example

Example 1:

Input: root = [3,1,4,3,null,1,5]

311543

Output: 4

Solution: Depth-First Search (DFS)

The problem can be solved efficiently using a recursive Depth-First Search. We traverse the tree, keeping track of the maximum value encountered in the path from the root to the current node.

Algorithm Steps

  • Create a recursive function `dfs(node, max_val)`.
  • Base Case: If `node` is null, return 0.
  • If the current node's value is greater than or equal to `max_val`, it's a "good" node. Increment a counter.
  • Update `max_val` to be the maximum of the current `max_val` and the node's value.
  • Recursively call `dfs` on the left and right children with the updated `max_val`.
  • The total number of good nodes is the sum of the results from the recursive calls, plus 1 if the current node is good.
311543
Good Nodes Found: 0
Visiting node 3. Max value in path is -Infinity.
Count Good Nodes in Binary Tree Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        
        def dfs(node, max_val):
            if not node:
                return 0
            
            res = 1 if node.val >= max_val else 0
            max_val = max(max_val, node.val)
            res += dfs(node.left, max_val)
            res += dfs(node.right, max_val)
            return res

        return dfs(root, root.val)