oneby7

Binary Trees Depth first: return a value up

364. Count Complete Tree Nodes

Medium

You are given root, the root node of a complete binary tree. Return the number of nodes in the tree.

In a complete binary tree, every level is full except possibly the last one. The nodes on the last level sit as far left as they can, with no gaps between them. A tree whose last level is full is complete too, and so is an empty tree.

Counting every node is the easy part. Try to count them in less than O(n) time, where n is the number of nodes.

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

5-43689112

Input: root = [8, 3, 11, -4, 6, 9, 2, 5]

Output: 8

Explanation: The first three levels are full and hold 1 + 2 + 4 = 7 nodes. The last level has one node, 5, at its far left. That makes 8 nodes.

Example 2

Input: root = []

Output: 0

Explanation: The tree has no nodes.

Example 3

-8-3-3-300-8

Input: root = [-3, -3, 0, -8, -3, 0, -8]

Output: 7

Explanation: All three levels are full. Values repeat, but each node counts once.

Check your understanding

Work out the answer for this input before you write any code.

root = [1, 2, 3, 4, 5, 6]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree is complete.

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.