Fundamentals/Visible Tree Node | Number of Visible Nodes
← PrevNext →
A node in a binary tree is "visible" if no node on the path from the root to it has a strictly greater value. Given a tree's root and the running maximum value seen so far on the path from a virtual ancestor, count the number of visible nodes in the subtree.
Input
root: the root of a binary tree (level-order array; null marks a missing child)
maxSoFar: the maximum value seen on the path before reaching root
Output
The number of visible nodes in the subtree.
Examples
Example 1
Inputroot = [1, 2, 3], maxSoFar = 1
Output3
Example 2
Inputroot = [1, 2, 3, 4, 5, null, 6], maxSoFar = 2
Output5
Constraints
A node is visible when its value is greater than or equal to every value on the path from the root to it.