Problem 442337 · easy · Phase 04 Non-Linear Data Structures

Count the Leaves

binary trees · recursion · leaf nodes

A leaf is a node with neither a left nor a right child. Given the root of a binary tree, return how many leaves it contains. An empty tree has 0 leaves; a lone root is 1 leaf.

Examples

      1
     / \
    2   3
   / \   \
  4   5   6

Input:  root = build_tree([1, 2, 3, 4, 5, None, 6])
Output: 3
Explanation: the leaves are 4, 5 and 6.
Input:  root = build_tree([7])
Output: 1

Constraints

  • 0 <= number of nodes <= 2000
  • Target complexity: O(n) time.

Goals

  • Recognise a leaf as a node with no children
  • Combine counts from both subtrees
  • Return 0 for an empty tree
Starting Python…