Sum of nodes at k-th level in a tree represented as string
Last Updated : 23 Jul, 2025
Given an integer k and a binary tree in string format. Every node of a tree has a value in the range of 0 to 9. The task is to find the sum of elements at the k-th level from the root. The root is at level 0. Tree is given in the form: (node value(left subtree)(right subtree))
Examples:
Input : s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))" , k = 2 Output : 14 Explanation: The tree representation is shown below:
Elements at level k = 2 are 6, 4, 1, 3 and the sum of the digits of these elements = 6 + 4 + 1 + 3 = 14
[Naive Approach] Using Pre-order traversal - O(n) Time and O(h) Space
The idea is to treat the string as tree without actually creating one, and simply traverse the string recursively in pre-ordermanner and consider nodes that are at level k only.
Note: This approach may give Stack Overflow error.
Below is the implementation of the above approach:
C++
// C++ implementation to find sum of// digits of elements at k-th level#include<bits/stdc++.h>usingnamespacestd;intkLevelSumRecur(int&i,strings,intk,intlevel){if(s[i]=='(')i++;// Find the value of current node.intval=0;while(i<s.length()&&s[i]!='('&&s[i]!=')'){val=val*10+(s[i]-'0');i++;}// Append the value of current node// only if it is at level k.val=(level==k)?val:0;intleft=0,right=0;// If left subtree existsif(i<s.length()&&s[i]=='('){left=kLevelSumRecur(i,s,k,level+1);}// if right subtree existsif(i<s.length()&&s[i]=='('){right=kLevelSumRecur(i,s,k,level+1);}// To take care of closing parenthesisi++;returnval+left+right;}// Function to find sum of digits// of elements at k-th levelintkLevelSum(strings,intk){inti=0;returnkLevelSumRecur(i,s,k,0);}intmain(){strings="(0(5(6()())(4()(9()())))(7(1()())(3()())))";intk=2;cout<<kLevelSum(s,k);return0;}
Java
// Java implementation to find sum of// digits of elements at k-th levelclassGfG{staticintkLevelSumRecur(int[]i,Strings,intk,intlevel){if(s.charAt(i[0])=='(')i[0]++;// Find the value of current node.intval=0;while(i[0]<s.length()&&s.charAt(i[0])!='('&&s.charAt(i[0])!=')'){val=val*10+(s.charAt(i[0])-'0');i[0]++;}// Append the value of current node// only if it is at level k.val=(level==k)?val:0;intleft=0,right=0;// If left subtree existsif(i[0]<s.length()&&s.charAt(i[0])=='('){left=kLevelSumRecur(i,s,k,level+1);}// if right subtree existsif(i[0]<s.length()&&s.charAt(i[0])=='('){right=kLevelSumRecur(i,s,k,level+1);}// To take care of closing parenthesisi[0]++;returnval+left+right;}// Function to find sum of digits// of elements at k-th levelstaticintkLevelSum(Strings,intk){int[]i={0};returnkLevelSumRecur(i,s,k,0);}publicstaticvoidmain(String[]args){Strings="(0(5(6()())(4()(9()())))(7(1()())(3()())))";intk=2;System.out.println(kLevelSum(s,k));}}
Python
# Python implementation to find sum of# digits of elements at k-th leveldefkLevelSumRecur(i,s,k,level):ifs[i[0]]=='(':i[0]+=1# Find the value of current node.val=0whilei[0]<len(s)ands[i[0]]!='('ands[i[0]]!=')':val=val*10+(ord(s[i[0]])-ord('0'))i[0]+=1# Append the value of current node# only if it is at level k.val=valiflevel==kelse0left,right=0,0# If left subtree existsifi[0]<len(s)ands[i[0]]=='(':left=kLevelSumRecur(i,s,k,level+1)# if right subtree existsifi[0]<len(s)ands[i[0]]=='(':right=kLevelSumRecur(i,s,k,level+1)# To take care of closing parenthesisi[0]+=1returnval+left+right# Function to find sum of digits# of elements at k-th leveldefkLevelSum(s,k):i=[0]returnkLevelSumRecur(i,s,k,0)if__name__=="__main__":s="(0(5(6()())(4()(9()())))(7(1()())(3()())))"k=2print(kLevelSum(s,k))
C#
// C# implementation to find sum of// digits of elements at k-th levelusingSystem;classGfG{staticintkLevelSumRecur(refinti,strings,intk,intlevel){if(s[i]=='(')i++;// Find the value of current node.intval=0;while(i<s.Length&&s[i]!='('&&s[i]!=')'){val=val*10+(s[i]-'0');i++;}// Append the value of current node// only if it is at level k.val=(level==k)?val:0;intleft=0,right=0;// If left subtree existsif(i<s.Length&&s[i]=='('){left=kLevelSumRecur(refi,s,k,level+1);}// if right subtree existsif(i<s.Length&&s[i]=='('){right=kLevelSumRecur(refi,s,k,level+1);}// To take care of closing parenthesisi++;returnval+left+right;}// Function to find sum of digits// of elements at k-th levelstaticintkLevelSum(strings,intk){inti=0;returnkLevelSumRecur(refi,s,k,0);}staticvoidMain(string[]args){strings="(0(5(6()())(4()(9()())))(7(1()())(3()())))";intk=2;Console.WriteLine(kLevelSum(s,k));}}
JavaScript
// JavaScript implementation to find sum of// digits of elements at k-th levelfunctionkLevelSumRecur(i,s,k,level){if(s[i[0]]==='(')i[0]++;// Find the value of current node.letval=0;while(i[0]<s.length&&s[i[0]]!=='('&&s[i[0]]!==')'){val=val*10+(s.charCodeAt(i[0])-'0'.charCodeAt(0));i[0]++;}// Append the value of current node// only if it is at level k.val=(level===k)?val:0;letleft=0,right=0;// If left subtree existsif(i[0]<s.length&&s[i[0]]==='('){left=kLevelSumRecur(i,s,k,level+1);}// if right subtree existsif(i[0]<s.length&&s[i[0]]==='('){right=kLevelSumRecur(i,s,k,level+1);}// To take care of closing parenthesisi[0]++;returnval+left+right;}// Function to find sum of digits// of elements at k-th levelfunctionkLevelSum(s,k){leti=[0];returnkLevelSumRecur(i,s,k,0);}consts="(0(5(6()())(4()(9()())))(7(1()())(3()())))";constk=2;console.log(kLevelSum(s,k));
Output
14
[Expected Approach] Using Iterative Method - O(n) Time and O(1) Space
The idea is to iterate over the string and use the brackets to find the level of the current node. If current character is '(', then increment the level. If current character is ')', then decrement the level.
Step by step approach:
Initialize two variables,say level = -1 and sum = 0
for each character 'ch' in 's'
if ch == '(' then increment the level.
else if ch == ')' then decrement the level.
else if level == k, then add the node value to sum.
return sum.
Below is the implementation of the above approach:
C++
// C++ implementation to find sum of// digits of elements at k-th level#include<bits/stdc++.h>usingnamespacestd;// Function to find sum of digits// of elements at k-th levelintkLevelSum(strings,intk){intlevel=-1;intsum=0;intn=s.length();for(inti=0;i<n;i++){// increasing level numberif(s[i]=='(')level++;// decreasing level numberelseif(s[i]==')')level--;// check if current level is// the desired level or notelseif(level==k){intval=0;// find the value of nodewhile(i<n&&s[i]!='('&&s[i]!=')'){val=val*10+(s[i]-'0');i++;}i--;sum+=val;}}returnsum;}intmain(){strings="(0(5(6()())(4()(9()())))(7(1()())(3()())))";intk=2;cout<<kLevelSum(s,k);return0;}
Java
// Java implementation to find sum of// digits of elements at k-th levelimportjava.util.*;classGfG{// Function to find sum of digits// of elements at k-th levelstaticintkLevelSum(Strings,intk){intlevel=-1;intsum=0;intn=s.length();for(inti=0;i<n;i++){// increasing level numberif(s.charAt(i)=='(')level++;// decreasing level numberelseif(s.charAt(i)==')')level--;// check if current level is// the desired level or notelseif(level==k){intval=0;// find the value of nodewhile(i<n&&s.charAt(i)!='('&&s.charAt(i)!=')'){val=val*10+(s.charAt(i)-'0');i++;}i--;sum+=val;}}returnsum;}publicstaticvoidmain(String[]args){Strings="(0(5(6()())(4()(9()())))(7(1()())(3()())))";intk=2;System.out.println(kLevelSum(s,k));}}
Python
# Python implementation to find sum of# digits of elements at k-th level# Function to find sum of digits# of elements at k-th leveldefkLevelSum(s,k):level=-1sum=0n=len(s)i=0whilei<n:# increasing level numberifs[i]=='(':level+=1# decreasing level numberelifs[i]==')':level-=1# check if current level is# the desired level or noteliflevel==k:val=0# find the value of nodewhilei<nands[i]!='('ands[i]!=')':val=val*10+(ord(s[i])-ord('0'))i+=1i-=1sum+=vali+=1returnsumif__name__=="__main__":s="(0(5(6()())(4()(9()())))(7(1()())(3()())))"k=2print(kLevelSum(s,k))
C#
// C# implementation to find sum of// digits of elements at k-th levelusingSystem;classGfG{// Function to find sum of digits// of elements at k-th levelstaticintkLevelSum(strings,intk){intlevel=-1;intsum=0;intn=s.Length;for(inti=0;i<n;i++){// increasing level numberif(s[i]=='(')level++;// decreasing level numberelseif(s[i]==')')level--;// check if current level is// the desired level or notelseif(level==k){intval=0;// find the value of nodewhile(i<n&&s[i]!='('&&s[i]!=')'){val=val*10+(s[i]-'0');i++;}i--;sum+=val;}}returnsum;}staticvoidMain(string[]args){strings="(0(5(6()())(4()(9()())))(7(1()())(3()())))";intk=2;Console.WriteLine(kLevelSum(s,k));}}
JavaScript
// JavaScript implementation to find sum of// digits of elements at k-th level// Function to find sum of digits// of elements at k-th levelfunctionkLevelSum(s,k){letlevel=-1;letsum=0;letn=s.length;for(leti=0;i<n;i++){// increasing level numberif(s[i]==='(')level++;// decreasing level numberelseif(s[i]===')')level--;// check if current level is// the desired level or notelseif(level===k){letval=0;// find the value of nodewhile(i<n&&s[i]!=='('&&s[i]!==')'){val=val*10+(s.charCodeAt(i)-'0'.charCodeAt(0));i++;}i--;sum+=val;}}returnsum;}consts="(0(5(6()())(4()(9()())))(7(1()())(3()())))";constk=2;console.log(kLevelSum(s,k));