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.
Input: root = [1,2,3,4,5,6] Output: 6
Input: root = [] Output: 0
Input: root = [1] Output: 1
- The number of nodes in the tree is in the range
[0, 5 * 104]
. 0 <= Node.val <= 5 * 104
- The tree is guaranteed to be complete.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
low = 0
high = 1
curr = root
root = TreeNode(left=TreeNode(), right=root)
while curr is not None:
low = (low << 1) + 1
high = (high << 1) + 1
curr = curr.right
while low < high:
mid = (low + high) // 2
curr = root
flag = True
for bit in bin(mid)[2:]:
if bit == '0':
curr = curr.left
else:
curr = curr.right
if curr is None:
flag = False
break
if flag:
low = mid + 1
else:
high = mid
return low - 1