Code Logo

Tree Count Leaves

Published at25 Jul 2026
Tree Traversal Easy 2 views
Like0

Given an array representing a complete binary tree in level-order, collect all leaf node values and return them in order. Leaf nodes are nodes that have no children — in the array representation, a node at index i is a leaf if its left child index (2i+1) is beyond the array bounds.

For example, in the tree [1, 2, 3, 4, 5, 6, 7], the leaves are 4, 5, 6, 7 (all at the bottom level). In [1, 2, 3, 4], the leaves are 3 and 4 (2 has a child, but 3 and 4 do not). An empty tree returns an empty array.

Leaf node identification is a fundamental tree operation. Leaves are the terminal nodes of a tree — they have no children and represent the end of every root-to-leaf path. In BST problems, leaves often serve as base cases for recursive algorithms.

The solution iterates through the array and checks each node. If its left child index is out of bounds, it is a leaf. Collect all such nodes into a result array.

Edge cases include an empty tree (return []), a single-node tree (the root is also a leaf), and a full tree where all leaves are at the same depth.

Example Input & Output

Example 1
Input
[1,2,3,4,5,6,7]
Output
4
Explanation

Leaves at 3,4,5,6

Example 2
Input
[1]
Output
1
Explanation

Root is leaf

Example 3
Input
[1,2,3,4,5]
Output
3
Explanation

Leaves at 2,3,4

Example 4
Input
[1,2,3,4]
Output
2
Explanation

Leaves at 2,3

Example 5
Input
[]
Output
0
Explanation

Empty

Algorithm Flow

Recommendation Algorithm Flow for Tree Count Leaves

Solution Approach

Iterate through the array and collect nodes whose children are beyond the array bounds.

function printLeaves(arr)
  leaves = []
  for i = 0 to length(arr) - 1
    if 2 * i + 1 >= length(arr) then add arr[i] to leaves
  return leaves

Loop through each index. A node is a leaf if its left child index (2i+1) is beyond the array length. In a complete binary tree, if the left child is out of bounds, the right child (2i+2) will also be out of bounds.

Time complexity is O(n), space complexity is O(n) for the result.

Best Answers

java
class Solution {
    public int solution(int[] nums) {
        if(nums.length==0)return 0;int c=0,n=nums.length;
        for(int i=0;i<n;i++){if(2*i+1>=n)c++;}
        return c;
    }
}