Count Good Nodes In Binary Tree

Counting Nodes which are Good in a Binary Tree

In a binary tree, a node x is considered a good node if, on the path from the root of the tree to x, no other node has a value greater than x. In other words, a node is good if its value is the largest (or equal to the largest) seen so far along its path from the root.

You are given the root of a binary tree, and the task is to calculate and return the total number of good nodes present in the tree.

Counting Good Node

Example 1

Example one of Good Node
Output of Example 1 of Good Node

Constraints:

  • 1 <= number of nodes in the tree <= 100
  • -100 <= Node.val <= 100

Maximum Depth of Binary Tree

Recommendation for Time and Space Complexity – You should aim for a solution with O(n) time and O(n) space, where n is the number of nodes in the given tree.

Hints for solving problems

Hint 1 :

A brute force solution would involve considering every node and checking if the path from the root to that node is valid, resulting in an O(n^2) time complexity. Can you think of a better approach?

Hint 2 :

We can use the Depth First Search (DFS) algorithm to traverse the tree. But can you think of a way to determine if the current node is a good node in a single traversal? Maybe we need to track a value while traversing the tree.

There are mainly 2 approach to solve this problem-

  1. Depth First Search Method
  2. Breadth First Search Method

1. Depth First Search Method

In this method, we traverse the tree recursively, keeping track of the maximum value seen so far along the path. At each node, we check if its value is greater than or equal to the maximum value and update the count accordingly. The maximum value is also updated as we move deeper into the tree.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

2. Breadth First Search Method

This approach uses a queue to perform a level-by-level traversal of the tree. Along with each node, we store the maximum value seen so far on its path. At each step, we compare the node’s value with the maximum value, update the count if it’s a good node, and propagate the updated maximum value to its children.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

More Articles