Binary Tree K level sum | Practice | GeeksforGeeks

Given a binary tree and a number K, the task is to find sum of tree nodes at level K. The Binary Tree is given in string form S: (node-value(left-subtree)(right-subtree)).
 
Example 1:
Input:
K = 2
S = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"
Output:
14
Explanation:
The Tree from the above String will be formed as:
                             0
                           /   \
                          5      7
                        /  \    /  \
                       6    4  1    3
                             \
                              9  
Sum of nodes at the 2nd level is 6+4+1+3 = 14.
Example 1:
Input:
K = 1
S = "(4(8()9())"
Output:
17
Explanation:
The Tree from the above String will be formed as:
                             4
                           /   \
                          8     9
Sum of nodes at the 1st level is 8+9 = 17.
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function kLevelSum() which takes an Integer K and a String S as input and returns the sum of all the node values at Kth level of the tree.
 
Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(1)
 
Constraints:
5 <= |S| <= 105
0 <= K <= 15
0
vrajeshmodi991 month ago
int kLevelSum(int K, string S) {
        
        int count=-1;
        int ans=0;
        int i=0;
        // for(int i=0;i<S.size();i++)
        while(i<S.size()){
            
            if(S[i] == '(')count+=1;
                
            else if(S[i] == ')')count-=1;
            
            if(count == K && S[i]!='(' && S[i]!=')')
            {
                int sum = S[i]-'0';
                i++;
                
                if(i>=S.size())return ans;
                
                while(S[i]>='0' && S[i]<='9')
                {
                    if(i>=S.size()){
                        return ans;
                    }
                    sum*=10;
                    sum += S[i]-'0';
                    i++;
                }
                
                ans+=sum;
                if(S[i]=='(')count++;
                if(S[i]==')')count--;
            }
            i++;
        }
        return ans;
    }
0
akashbharatpal3 months ago
total time taken 0.0
 
class Solution { public:   int kLevelSum(int K, string S) {       int level=-1,sum=0,i=0,n=0;       while(i<S.length()){           if(S[i]=='('){level++;}           else if(S[i]==')'){level--;}           else if(level==K) {               while(S[i]<='9'&&S[i]>='0'){n=n*10+(S[i]-'0');i++;}               sum+=n;               n=0;               i--;           }           i++;       }       return sum;   }};
+1
xyz9377 months ago
please check test case.
for this test where is closing brackets for first opening.
1(4(90()1())
0
ANAS MALVAT8 months ago
ANAS MALVAT
               int ret  = 0;    int chkl;    void chk(string s,int ind ,int lev)    {        if(ind == s.length())            return;         if(s[ind] == '(')            lev += 1;         if( s[ind] >= '0' and s[ind] <= '9' ){            int cur = 0;            while(ind < s.length() and s[ind] >= '0' and s[ind] <= '9'){                cur = cur * 10 + s[ind++] - '0';            }            ind --;            if(lev == chkl)                ret += cur;        }         if( s[ind] == ')' )            lev -= 1;        chk(s,ind + 1,lev);    }    int kLevelSum(int K, string S) {        // code here        chkl = K;        chk(S,0,-1);        return ret;    }
0
Puru Bhargava8 months ago
Puru Bhargava
Expected Time Complexity: O(|S|)Expected Auxiliary Space: O(1) https://uploads.disquscdn.c...
0
peeyush_thakur9 months ago
peeyush_thakur
Execution time:0.0sint kLevelSum(int K, string S) {        int total=0;int k=0;        for(int i=1;i<s.length();i++) {="" if(s[i]="='(')" {k++;}="" else="" if(s[i]="=')')" {k--;}="" else="" if(k="=K)" {="" int="" l="0;" while(s[i]<="9" &&="" s[i]="">='0')                {                    l=l*10+(S[i]-'0');i++;                }                total+=l;                i--;            }        }        return total;    }
0
Sarvesh Raut10 months ago
Sarvesh Raut
C++ short and concise :
https://uploads.disquscdn.c...
0
anup dogrial10 months ago
anup dogrial
https://uploads.disquscdn.c...
0
Aniket patel10 months ago
Aniket patel
class Solution {  public:    int kLevelSum(int K, string S)     {        int sum=0,level=-1;        string res="";        for(int i=0;i<s.length();i++) {="" res="" ;="" while(level="=K" and="" s[i]="">='0' and S[i]<='9')            {                res+=S[i];                i++;            }            if(res.length())            {                sum+=stoi(res);            }            if(S[i]=='(')            {                level++;            }            else if(S[i]==')')            {                level--;            }        }        return(sum);    }};https://practice.geeksforge...
0
Debojyoti Sinha1 year ago
Debojyoti Sinha
Correct Answer.Correct AnswerExecution Time:0.01
class Solution{    public:    int kLevelSum(int K, string S)     {        int level = -1;        int res = 0;                        for(int i = 0; i < S.size(); i++)        {            if(isdigit(S[i]))            {                if(level == K)                {                    int num = 0;                                        while(i < S.size())                    {                        if(S[i] == ')' or S[i] == '(')                        {                            i--;                                                        break;                        }                                                num = num * 10 + (S[i] - '0');                                                i++;                    }                                        res += num;                }            }            else            {                if(S[i] == '(')                {                    level++;                }                else if(S[i] == ')')                {                    level--;                }            }        }                return res;    }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.