Open In App

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

Last Updated : 20 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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. We need 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 : 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

Implementation:

C++




// 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 level
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 program to test above
int main()
{
    string tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
    int k = 2;
    cout << sumAtKthLevel(tree, k);
    return 0;
}


Java




// Java implementation to find sum of
// digits of elements at k-th level
class GfG {
 
// Function to find sum of digits
// of elements at k-th level
static 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 above
public 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




# Python3 implementation to find sum of
# digits of elements at k-th level
 
# Function to find sum of digits
# of elements at k-th level
def 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 Code
if __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#




// 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 level
static 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 code
public 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


Javascript




<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 level
function 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 code
let 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) 
Auxiliary Space: O(1)

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 that are at level k only. 

Following is the implementation of the same:

C++




// 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 level
int 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 above
int 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




// Java implementation to find sum of
// digits of elements at k-th level
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.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




# 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 level
def 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 above
tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"
k = 2
i = [0]
print(sumAtKthLevel(tree, k, i, 0))
 
# This code is contributed by SHUBHAMSINGH10


C#




// C# implementation to find sum of
// digits of elements at k-th level
using 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


Javascript




<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), the time complexity of this algorithm is O(n) as we need to traverse all the nodes of the tree in order to get the sum of digits of elements at the kth level.
Auxiliary Space: O(1), If we consider the recursive call stack then it will be O(K).

 



Previous Article
Next Article

Similar Reads

Product of nodes at k-th level in a tree represented as string using Recursion
Prerequisite: Product of nodes at k-th level in a tree represented as stringGiven 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 product of elements at K-th level from the root. The root is at level 0.Note: Tree is given in the form: (node value(left subtree)(right subtree))Ex
5 min read
Product of nodes at k-th level in a tree represented as string
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 product of elements at K-th level from root. The root is at level 0. Note : 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 Out
6 min read
Calculate sum of all nodes present in a level for each level of a Tree
Given a Generic Tree consisting of N nodes (rooted at 0) where each node is associated with a value, the task for each level of the Tree is to find the sum of all node values present at that level of the tree. Examples: Input: node_number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, node_values = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 } Output: Sum of level 0 = 2S
14 min read
Print the nodes corresponding to the level value for each level of a Binary Tree
Given a Binary Tree, the task for each level L is to print the Lth node of the tree. If the Lth node is not present for any level, print -1. Note: Consider the root node to be at the level 1 of the binary tree. Examples: Input: Below is the given Tree: Output:Level 1: 1Level 2: 3 Level 3: 6Level 4: 11Explanation:For the first level, the 1st node is
15 min read
Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
Given a Binary Tree, the task is for each level is to print the total number of nodes from all lower levels which are less than or equal to every node present at that level. Examples: Input: Below is the given tree: 4 / \ 3 5 / \ / \ 10 2 3 1 Output: 4 3 0Explanation:Nodes in level 1 has 4 nodes as (3) in level 2 and (2, 3, 1) in level 3. Nodes in
11 min read
Difference between sums of odd level and even level nodes in an N-ary Tree
Given an N-ary Tree rooted at 1, the task is to find the difference between the sum of nodes at the odd level and the sum of nodes at even level. Examples: Input: 4 / | \ 2 3 -5 / \ / \ -1 3 -2 6Output: 10Explanation:Sum of nodes at even levels = 2 + 3 + (-5) = 0Sum of nodes at odd levels = 4 + (-1) + 3 + (-2) + 6 = 10Hence, the required difference
9 min read
Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
Given a Binary Search Tree, the task is to print the nodes of the BST in the following order: If the BST contains levels numbered from 1 to N then, the printing order is level 1, level N, level 2, level N - 1, and so on.The top-level order (1, 2, …) nodes are printed from left to right, while the bottom level order (N, N-1, ...) nodes are printed f
15+ min read
Modify a Binary Tree by adding a level of nodes with given value at a specified level
Given a Binary Tree consisting of N nodes and two integers K and L, the task is to add one row of nodes of value K at the Lth level, such that the orientation of the original tree remains unchanged. Examples: Input: K = 1, L = 2 Output:11 12 34 5 6 Explanation:Below is the tree after inserting node with value 1 in the K(= 2) th level. Input: K = 1,
15+ min read
Difference between sums of odd level and even level nodes of a Binary Tree
Given a Binary Tree, find the difference between the sum of nodes at odd level and the sum of nodes at even level. Consider root as level 1, left and right children of root as level 2 and so on. For example, in the following tree, sum of nodes at odd level is (5 + 1 + 4 + 8) which is 18. And sum of nodes at even level is (2 + 6 + 3 + 7 + 9) which i
15+ min read
Check if all nodes of the Binary Tree can be represented as sum of two primes
Given a binary tree of N nodes with odd value. The task is to check whether all the nodes of the tree can be represented as the sum of the two prime numbers or not. Examples: Input: Output: Yes Explanation: All the nodes in the tree can be represented as the sum of two prime numbers as: 9 = 2 + 7 15 = 2 +13 7 = 2 + 5 19 = 2 + 17 25 = 2 + 23 13 = 11
11 min read
Article Tags :
Practice Tags :