Skip to main content
Back to ChallengesCount Leaf NodesEasy 15 min

Count Leaf Nodes

Given the root of a binary tree, return the **number of leaf nodes**.

A **leaf node** is a node with no children (both left and right are null).

Examples

Input: root = [1,2,3,4,5]
Output: 3
Leaves are 4, 5, and 3.
Input: root = [1]
Output: 1
Root itself is the only leaf.

Constraints

  • Number of nodes in [1, 10^4]
  • Node values are integers

Complexity Analysis

Time
O(n)
every node is visited.
Space
O(h)
recursive stack.

Test Cases

#1 Five-node tree
Input: [1,2,3,4,5]
Expected: 3
#2 Single node
Input: [1]
Expected: 1
#3 Root + two leaves
Input: [1,2,3]
Expected: 2
#4 Left-skewed branch
Input: [1,2,null,3]
Expected: 1
JavaScript
Output
Click "Run Code" to see output here...