Friedrich Ewald My Personal Website

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)


About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.