Sum of nodes at k-th level in a tree represented as string

14 Mar, 2022
Given an integer ‘K’ and a binary tree in string format. Every node of a tree has value in range from 0 to 9. We need to find sum of elements at K-th level from root. The root is at level 0. Tree is given in the form: (node value(left subtree)(right subtree)) 
Examples: 
Input : tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))" 
        k = 2
Output : 14
Its tree representation is shown below
Elements at level k = 2 are 6, 4, 1, 3
sum of the digits of these elements = 6+4+1+3 = 14 


Input : tree = "(8(3(2()())(6(5()())()))(5(10()())(7(13()())())))" 
        k = 3
Output : 9
Elements at level k = 3 are 5, 1 and 3
sum of digits of these elements = 5+1+3 = 9
1. Input 'tree' in string format and level k
2. Initialize level = -1 and sum = 0
3. for each character 'ch' in 'tree'
   3.1  if ch == '(' then
        --> level++
   3.2  else if ch == ')' then
        --> level--
   3.3  else
        if level == k then
           sum = sum + (ch-'0')
4. Print sum
C++
Java
Python3
C#
Javascript
// C++ implementation to find sum of// digits of elements at k-th level#include <bits/stdc++.h>using namespace std; // Function to find sum of digits// of elements at k-th levelint sumAtKthLevel(string tree, int k){    int level = -1;    int sum = 0;  // Initialize result    int n = tree.length();     for (int i=0; i<n; i++)    {        // increasing level number        if (tree[i] == '(')            level++;         // decreasing level number        else if (tree[i] == ')')            level--;         else        {            // check if current level is            // the desired level or not            if (level == k)                sum += (tree[i]-'0');        }    }     // required sum    return sum;} // Driver program to test aboveint main(){    string tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";    int k = 2;    cout << sumAtKthLevel(tree, k);    return 0;}
// Java implementation to find sum of// digits of elements at k-th levelclass GfG { // Function to find sum of digits// of elements at k-th levelstatic int sumAtKthLevel(String tree, int k){    int level = -1;    int sum = 0; // Initialize result    int n = tree.length();     for (int i=0; i<n; i++)    {        // increasing level number        if (tree.charAt(i) == '(')            level++;         // decreasing level number        else if (tree.charAt(i) == ')')            level--;         else        {            // check if current level is            // the desired level or not            if (level == k)                sum += (tree.charAt(i)-'0');        }    }     // required sum    return sum;} // Driver program to test abovepublic static void main(String[] args){    String tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";    int k = 2;    System.out.println(sumAtKthLevel(tree, k));}}
# Python3 implementation to find sum of# digits of elements at k-th level # Function to find sum of digits# of elements at k-th leveldef sumAtKthLevel(tree, k) :     level = -1    sum = 0 # Initialize result    n = len(tree)     for i in range(n):                 # increasing level number        if (tree[i] == '(') :            level += 1         # decreasing level number        else if (tree[i] == ')'):            level -= 1         else:                     # check if current level is            # the desired level or not            if (level == k) :                sum += (ord(tree[i]) - ord('0'))             # required sum    return sum # Driver Codeif __name__ == '__main__':    tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"    k = 2    print(sumAtKthLevel(tree, k)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# implementation to find sum of// digits of elements at k-th level using System;class GfG { // Function to find sum of digits// of elements at k-th levelstatic int sumAtKthLevel(string tree, int k){    int level = -1;    int sum = 0; // Initialize result    int n = tree.Length;     for (int i = 0; i < n; i++)    {        // increasing level number        if (tree[i] == '(')            level++;         // decreasing level number        else if (tree[i] == ')')            level--;         else        {            // check if current level is            // the desired level or not            if (level == k)                sum += (tree[i]-'0');        }    }     // required sum    return sum;} // Driver codepublic static void Main(){    string tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";    int k = 2;    Console.Write(sumAtKthLevel(tree, k));}} // This code is contributed by Ita_c
<script> // Javascript implementation to find sum of// digits of elements at k-th level     // Function to find sum of digits// of elements at k-th levelfunction sumAtKthLevel(tree, k){    let level = -1;         // Initialize result    let sum = 0;    let n = tree.length;         for(let i = 0; i < n; i++)    {                 // Increasing level number        if (tree[i] == '(')            level++;             // Decreasing level number        else if (tree[i] == ')')            level--;             else        {                         // Check if current level is            // the desired level or not            if (level == k)                sum += (tree[i] - '0');        }    }         // Required sum    return sum;} // Driver codelet tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";let k = 2; document.write(sumAtKthLevel(tree, k)); // This code is contributed by avanitrachhadiya2155 </script>
Output: 
14
Time Complexity: O(n) 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Recursive Method: The idea is to treat the string as tree without actually creating one, and simply traverse the string recursively in Postorder Fashion and consider nodes which are at level k only. 
Following is the implementation of the same:
C++
Java
Python
C#
Javascript
// C++ implementation to find sum of// digits of elements at k-th level#include <bits/stdc++.h>using namespace std; // Recursive Function to find sum of digits// of elements at k-th levelint sumAtKthLevel(string tree, int k,int &i,int level){            if(tree[i++]=='(')    {             // if subtree is null, just like if root == NULL      if(tree[i] == ')')           return 0;                      int sum=0;             // Consider only level k node to be part of the sum      if(level == k)        sum = tree[i]-'0';             // Recur for Left Subtree      int leftsum = sumAtKthLevel(tree,k,++i,level+1);             // Recur for Right Subtree      int rightsum = sumAtKthLevel(tree,k,++i,level+1);             // Taking care of ')' after left and right subtree      ++i;      return sum+leftsum+rightsum;           }} // Driver program to test aboveint main(){    string tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";    int k = 2;        int i=0;    cout << sumAtKthLevel(tree, k,i,0);    return 0;}
// Java implementation to find sum of// digits of elements at k-th levelclass GFG{    static int i;     // Recursive Function to find sum of digits    // of elements at k-th level    static int sumAtKthLevel(String tree, int k, int level)    {         if (tree.charAt(i++) == '(')        {             // if subtree is null, just like if root == null            if (tree.charAt(i) == ')')                return 0;             int sum = 0;             // Consider only level k node to be part of the sum            if (level == k)                sum = tree.charAt(i) - '0';             // Recur for Left Subtree            ++i;            int leftsum = sumAtKthLevel(tree, k, level + 1);             // Recur for Right Subtree            ++i;            int rightsum = sumAtKthLevel(tree, k, level + 1);             // Taking care of ')' after left and right subtree            ++i;            return sum + leftsum + rightsum;        }        return Integer.MIN_VALUE;    }     // Driver code    public static void main(String[] args)    {        String tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";        int k = 2;        i = 0;        System.out.print(sumAtKthLevel(tree, k, 0));    }} // This code is contributed by 29AjayKumar
# Python implementation to find sum of# digits of elements at k-th level # Recursive Function to find sum of digits# of elements at k-th leveldef sumAtKthLevel(tree, k, i, level):         if(tree[i[0]] == '('):        i[0] += 1                 # if subtree is null, just like if root == NULL        if(tree[i[0]] == ')'):            return 0                            sum = 0                 # Consider only level k node to be part of the sum        if(level == k):            sum = int(tree[i[0]])                     # Recur for Left Subtree        i[0] += 1        leftsum = sumAtKthLevel(tree, k, i, level + 1)                     # Recur for Right Subtree        i[0] += 1        rightsum = sumAtKthLevel(tree, k, i, level + 1)                     # Taking care of ')' after left and right subtree        i[0] += 1        return sum + leftsum + rightsum         # Driver program to test abovetree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"k = 2i = [0]print(sumAtKthLevel(tree, k, i, 0)) # This code is contributed by SHUBHAMSINGH10
// C# implementation to find sum of// digits of elements at k-th levelusing System; class GFG{    static int i;     // Recursive Function to find sum of digits    // of elements at k-th level    static int sumAtKthLevel(String tree, int k, int level)    {         if (tree[i++] == '(')        {             // if subtree is null, just like if root == null            if (tree[i] == ')')                return 0;             int sum = 0;             // Consider only level k node to be part of the sum            if (level == k)                sum = tree[i] - '0';             // Recur for Left Subtree            ++i;            int leftsum = sumAtKthLevel(tree, k, level + 1);             // Recur for Right Subtree            ++i;            int rightsum = sumAtKthLevel(tree, k, level + 1);             // Taking care of ')' after left and right subtree            ++i;            return sum + leftsum + rightsum;        }        return int.MinValue;    }     // Driver code    public static void Main(String[] args)    {        String tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";        int k = 2;        i = 0;        Console.Write(sumAtKthLevel(tree, k, 0));    }} // This code is contributed by Rajput-Ji
<script>// Javascript implementation to find sum of// digits of elements at k-th level         // Recursive Function to find sum of digits    // of elements at k-th level    function sumAtKthLevel(tree,k,level)    {        if (tree[i++] == '(')        {              // if subtree is null, just like if root == null            if (tree[i] == ')')                return 0;              let sum = 0;              // Consider only level k node to be part of the sum            if (level == k)                sum = tree[i] - '0';              // Recur for Left Subtree            ++i;            let leftsum = sumAtKthLevel(tree, k, level + 1);              // Recur for Right Subtree            ++i;            let rightsum = sumAtKthLevel(tree, k, level + 1);              // Taking care of ')' after left and right subtree            ++i;            return sum + leftsum + rightsum;        }        return Number.MIN_VALUE;    }          // Driver code    let tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";    let k = 2;    let i = 0;    document.write(sumAtKthLevel(tree, k, 0));         // This code is contributed by rag2127</script>
Output : 
14
Time Complexity: O(n) 
Sum of nodes at k-th level in a tree represented as string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersSum of nodes at k-th level in a tree represented as string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:43•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cRll97diO9o" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
prerna saini
ukasp
SHUBHAMSINGH10
Ankur Goel
29AjayKumar
Rajput-Ji
avanitrachhadiya2155
rag2127
simmytarika5
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
A program to check if a binary tree is BST or not
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree
Lowest Common Ancestor in a Binary Tree | Set 1