#222

Count Complete Tree Nodes

newbie · 260 · lc easy +19 · verified · 72.1% accepted · 9,456 likes · top 81%

play →

Description

Count the nodes in the complete binary tree rooted at root.

A complete binary tree fills every level except possibly the last, where nodes are packed as far left as possible; the last level holds between 1 and 2h nodes at height h.

Aim for an algorithm faster than O(n).

Example 1:

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

Example 2:

Input: root = []
Output: 0

Example 3:

Input: root = [1]
Output: 1

Code

1
2
3
4
5
6
7
8
9