Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Design an algorithm that runs in less than O(n) time complexity.
Output: 6
Input: root = []
Output: 0
Input: root = [1]
Output: 1
The most straightforward method to count all the nodes in a tree is to traverse the tree and count each node. In a normal binary tree, this approach works perfectly fine.
Given the properties of a complete tree, we can use a more efficient method leveraging the structure. The idea is to take advantage of the depth of the tree and binary search to determine missing nodes in the last level.