Count Good Nodes in Binary Tree
MediumP3Coding
In a binary tree, a node X is good if no node on the path from the root to X has a value greater than X. The root is always good. Given the root of a binary tree, return the number of good nodes.
Example 1
- Input
- root = [3,1,4,3,null,1,5]
- Output
- 4
- Why
- The good nodes are 3 (root), 4, 3 (left-left) and 5.
Example 2
- Input
- root = [3,3,null,4,2]
- Output
- 3
Example 3
- Input
- root = [1]
- Output
- 1
Constraints
- 1 <= number of nodes <= 10^5
- -10^4 <= Node.val <= 10^4
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.