Leetcode: Count Complete Tree Nodes
Given a perfect binary tree, count the number of nodes with an algorithm that has less than O(n)
time complexity.
# 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:
if root is None:
return 0
l = self.count_left(root)
r = self.count_right(root)
if l == r:
return pow(2, l) - 1
else:
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
def count_left(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
return 1 + self.count_left(root.left)
def count_right(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
return 1 + self.count_right(root.right)