Practice/Google/Leetcode 222. Count Complete Tree Nodes
CodingMust
You are given the root of a complete binary tree. Your task is to calculate and return the total number of nodes in the tree.
A complete binary tree is a special type of binary tree where:
The challenge is to solve this problem more efficiently than O(n) time complexity by leveraging the properties of a complete binary tree. A naive solution would visit every node, but you can do better by taking advantage of the tree's structure.
Example 1:
Input: root = [1,2,3,4,5,6] 1 / \ 2 3 / \ / 4 5 6 Output: 6 Explanation: The tree has 6 nodes in total.
Example 2:
Input: root = [] Output: 0 Explanation: An empty tree has no nodes.
Example 3:
Input: root = [1] Output: 1 Explanation: A single node tree contains exactly one node.
Example 4:
Input: root = [1,2,3,4,5,6,7] 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 7 Explanation: This is a perfect binary tree with all levels completely filled.