904. Count Good Nodes in Binary Tree

MediumTreesBinary TreeDFS

Given the root of a binary tree, a node X is 'good' if no node on the path from the root to X has a value strictly greater than X. Return the number of good nodes. The root is always good. The tree is given as a level-order array.

Input: A level-order array of the tree.

Output: Integer — the number of good nodes.

Examples

Example 1
Input: [3,1,4,3,null,1,5]
Output: 4
Explanation: Good nodes: 3 (root), 4, 5, and the deeper 3.
Example 2
Input: [3,3,null,4,2]
Output: 3
Explanation: Three good nodes.
Example 3
Input: [1]
Output: 1
Explanation: Root is good.

Constraints

Asked by

MicrosoftMetaAmazonGoogle
Solve this problem in the editor →