Binary Trees Depth first: return a value up
350. Count Good Nodes in Binary Tree
You are given root, the root node of a binary tree. A node is good when no node on the path from the
root down to it has a greater value. Return the number of good nodes in the tree.
The path to a node starts at the root and ends at the node itself, so the root is always good. A node whose value equals the largest value above it is good too. Only a strictly greater value above a node makes it not good.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [6, 2, 9, 6, 7, null, 12, null, null, 5]
5Explanation: The good nodes are the root 6, then 9, 12, 7 and the lower 6, which only ties the root. 2 is not good because 6 is above it, and 5 is not good because 6 and 7 are above it.
Example 2
Input: root = [-5, -8, -5, null, -3]
3Explanation: The root −5 is good, and so is the other −5, which ties it. −3 is good too: the largest value above it is −5, and −3 is greater. −8 is not good.
Example 3
Input: root = [8, null, 5, null, 7, null, 9]
2Explanation: Only 8 and 9 are good. 7 is greater than its parent 5, but the root 8 is above it as well.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
Clarifying questions
What you would ask an interviewer before writing any code.