oneby7

Binary Trees Depth first: return a value up

350. Count Good Nodes in Binary Tree

Medium

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

62576912

Input: root = [6, 2, 9, 6, 7, null, 12, null, null, 5]

Output: 5

Explanation: 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

-8-3-5-5

Input: root = [-5, -8, -5, null, -3]

Output: 3

Explanation: 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

8579

Input: root = [8, null, 5, null, 7, null, 9]

Output: 2

Explanation: 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.

root = [5, 5, 2, 4, 9, 3, 5]

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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.