Code Logo

Tree Node Count

Published at25 Jul 2026
Easy 0 views
Like0

Given a comma-separated string representing a tree, count the number of nodes.

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
Recommendation Algorithm Flow for Tree Node Count

Solution Approach

function solution(s) {
  return s ? s.split(',').length : 0;
}

Best Answers

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