EasyBinary SearchBit ManipulationTreeBinary Tree

Count Complete Tree Nodes

LeetCode
1 approach, code in all languages

You are given the root of a complete binary tree. In a complete tree every level is fully filled except possibly the last, and the last level is packed as far left as possible.

Return the total number of nodes. A plain traversal is O(n); the goal here is to exploit the completeness property to do better.

Example 1

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

Output: 6

The tree has two full levels plus two extra nodes on the last level.

Example 2

Input: root = [1]

Output: 1

A single root node counts as one.

Constraints

  • The number of nodes in the tree is in the range [0, 5 * 10^4].
  • 0 <= Node.val <= 5 * 10^4
  • The tree is guaranteed to be complete.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now