Skip to main content

Count Good Nodes in Binary Tree

Medium
Data Structures and Algorithms
Editorial
Topics:
Binary Tree
Depth-First Search
Tree

Implement goodNodes to inspect the binary tree given by root. A node is called good when its value is greater than or equal to every value on the path from the root to that node, including the node itself and the root. The root is therefore good whenever the tree is non-empty.

Return the total number of good nodes in root. A missing child does not represent a node, and an empty tree has no good nodes.

Example 1:

Input: root = [6,2,9,null,4,7,11]
Output: 3
Explanation: The root 6 is good, as are 9 and 11. The other nodes each have an earlier, larger value on their root-to-node path.

Example 2:

Input: root = [5,8,3,7,null,null,4]
Output: 2
Explanation: The root 5 and node 8 are good. Node 7 is below 8, while nodes 3 and 4 are below the earlier value 5, so they are not good.

Example 3:

Input: root = []
Output: 0
Explanation: The tree is empty, so there are no nodes to count.

Constraints:

  • 0 <= number of nodes in root <= 10^5
  • -10^4 <= node value <= 10^4
  • Each node has at most one left child and one right child
  • root represents a valid binary tree in level-order form
  • The tree contains no cycles

Need help or want more practice?

Practise in an interviewGet AI Coach help