# Count Good Nodes in Binary Tree

Category

Binary Tree - DFS

Checkbox

Checkbox

Difficulty

Medium

Index

35

Key Ideas

The key idea to solve the given problem in LeetCode-75 is to perform a depth-first search (DFS) traversal of the binary tree while keeping track of the maximum value encountered so far, and incrementing a count whenever a node's value is greater than or equal to the maximum value.

Problem Number

1448

Problem Summary

## Problem Summary:
The "Count Good Nodes in Binary Tree" problem requires counting the number of nodes in a binary tree that are considered good. A node is considered good if its value is greater than or equal to the maximum value in its path from the root to that node.
## Key Pitfalls:
- It is important to correctly implement the depth-first search (DFS) algorithm to traverse the binary tree and track the maximum value in each path.
- Be careful not to count a node as good if its value is less than the maximum value in its path, as the condition for being a good node is that it should be greater than or equal to the maximum value.
- Handle edge cases appropriately, such as an empty tree or a tree with only one node.

Solution Summary

To solve the problem of counting good nodes in a binary tree, one possible approach is to use depth-first search (DFS). Starting from the root, we traverse the tree and keep track of the maximum value encountered so far. At each node, if its value is greater than or equal to the maximum value, we increment the count of good nodes. We then recursively traverse the left and right subtrees, updating the maximum value as we go. By the end, the count will represent the number of good nodes in the binary tree. This solution has a time complexity of O(N), where N is the number of nodes in the tree, and a space complexity of O(H), where H is the height of the tree.

Tags

Tree

Depth-First Search

Breadth-First Search