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.
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
Constraints:
text
The number of nodes in the tree is in the range [0, 5 * 10⁴].
0 <= Node.val <= 5 * 10⁴
The tree is guaranteed to be complete.
Deliverable
Implement Solution.countNodes in /app/solution.py using Python 3.12.
Keep the supplied class and method signature. The file is the only submitted artifact.
The evaluator instantiates Solution and invokes this method with the problem's inputs;
do not read standard input or write a command-line program.
python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
The standard library, lctk 0.0.6 (LeetCode tree/list helpers), sortedcontainers 2.4.0,
NumPy 2.4.3, SciPy 1.17.1, and six 1.17.0 are available. Standard LeetCode imports,
including List, Optional, TreeNode and ListNode, are provided by the starter file.
Your solution must pass every hidden test. For a correct solution, the evaluator also
measures CPU runtime over 128 repetitions per test using independent copies of the
inputs, and compares it with passing reference solutions measured in the same environment.
Aim for an efficient algorithm. Wrong solutions receive zero efficiency credit.