PIXELBANKv9.1.0
Menu

Count Good Nodes in Binary Tree

A node is good if from the root to that node, there is no node with a value greater than it.

Given a binary tree (level-order array), return the count of good nodes.

Example:

Input:
3,1,4,3,null,1,5
Output:
4
Reasoning:
  • The binary tree is constructed from the level-order array: the root node is 3, its children are 1 and 4, and so on.
  • We start from the root node and traverse down, checking each node's value against the maximum value seen so far: the root node 3 is good, its child node 1 is good because 1<31 < 3, and the child node 4 is not good because 4>34 > 3.
  • For each node, we recursively apply this check to its children, counting the good nodes: the node 3 has a good child node 1, and the node 1 has a good child node 1 (because 1<31 < 3 and 1<11 < 1 is not considered), and the node 4 has good child nodes 3 and 5 (because 3<43 < 4 and 5<45 < 4 is not considered, but 3<43 < 4 and 5>45 > 4).
  • The total count of good nodes is 1+1+1+1=41 + 1 + 1 + 1 = 4, where each 1 represents a good node: the root node 3, and the nodes 1, 1, and 3.

Constraints:

  • 1 <= number of nodes <= 10^5
solution.py

Test Results

0/0
Run code to see test results.
Count Good Nodes in Binary Tree - Medium | PixelBank