Count Good Nodes in Binary Tree
TreesDFS
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]
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.
Good Nodes Found: 0
Visiting node 3. Max value in path is -Infinity.
Count Good Nodes in Binary Tree Solution