Code Logo

Tree Node Count

Published at25 Jul 2026
Binary Tree Easy 0 views
Like0

Given an array representing a complete binary tree stored in level-order, count the total number of nodes in the tree. The array uses the standard heap indexing where the root is at index 0, the left child of node i is at 2i+1, and the right child is at 2i+2. Nodes that do not exist are represented by -1 or are simply absent.

For example, the tree [1, 2, 3, 4, 5, 6, 7] has 7 nodes. The tree [1, 2, 3, 4] has 4 nodes. An empty array represents an empty tree with 0 nodes. A single-element array [5] has 1 node.

Counting nodes is one of the most fundamental tree operations. It serves as a building block for computing tree statistics like the sum of all values, the average value per level, and the tree's density. In a real tree data structure, counting nodes typically requires a traversal that visits every node once.

For an array-based tree representation, the count is simply the number of elements in the array. This is because the array stores every node explicitly — non-existent nodes that are between existing nodes cannot be skipped in a complete tree representation. Therefore, the node count equals the array length.

Edge cases include an empty array (return 0), a single-element array (return 1), and trees where some internal nodes have only one child (the array length still equals the total node count).

Example Input & Output

Example 1
Input
"1"
Output
1
Example 2
Input
"1,2,3"
Output
3
Example 3
Input
"1,2,3,4,5"
Output
5
Example 4
Input
""
Output
0
Example 5
Input
"a,b,c"
Output
3

Algorithm Flow

Recommendation Algorithm Flow for Tree Node Count

Solution Approach

Return the length of the array, which equals the number of nodes.

function solution(arr) {
  return arr.length;
}

In an array-based complete binary tree representation, every element in the array corresponds to a node. The root is at index 0, and nodes are placed in level order. Therefore, the total number of nodes is simply the array length.

Time complexity is O(1) since array length is a pre-computed property in most languages. Space complexity is O(1).

Best Answers

java
class Solution {
    public int solution(String s) {
        if(s.isEmpty())return 0;return s.split(",",-1).length;
    }
}