Open In App

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

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
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. 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:

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

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-order manner 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>
using namespace std;

int kLevelSumRecur(int &i, string s, int k, int level) { 
 
    if (s[i] == '(') i++;
    
    // Find the value of current node.
    int val = 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;
    
    int left = 0, right = 0;
    
    // If left subtree exists
    if (i<s.length() && s[i]=='(') {
        left = kLevelSumRecur(i, s, k, level+1);
    }
    
    // if right subtree exists
    if (i<s.length() && s[i]=='(') {
        right = kLevelSumRecur(i, s, k, level+1);
    }
    
    // To take care of closing parenthesis
    i++;
    
    return val + left + right;
} 

// Function to find sum of digits
// of elements at k-th level
int kLevelSum(string s, int k) {
    
    int i = 0;
    return kLevelSumRecur(i, s, k, 0);
}

int main() {
    string s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
    int k = 2;
    cout << kLevelSum(s, k);
    return 0;
}
Java
// Java implementation to find sum of
// digits of elements at k-th level

class GfG {

    static int kLevelSumRecur(int[] i, 
                              String s, int k, int level) {

        if (s.charAt(i[0]) == '(') i[0]++;

        // Find the value of current node.
        int val = 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;

        int left = 0, right = 0;

        // If left subtree exists
        if (i[0] < s.length() && s.charAt(i[0]) == '(') {
            left = kLevelSumRecur(i, s, k, level + 1);
        }

        // if right subtree exists
        if (i[0] < s.length() && s.charAt(i[0]) == '(') {
            right = kLevelSumRecur(i, s, k, level + 1);
        }

        // To take care of closing parenthesis
        i[0]++;

        return val + left + right;
    }

    // Function to find sum of digits
    // of elements at k-th level
    static int kLevelSum(String s, int k) {
        int[] i = {0};
        return kLevelSumRecur(i, s, k, 0);
    }

    public static void main(String[] args) {
        String s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
        int k = 2;
        System.out.println(kLevelSum(s, k));
    }
}
Python
# Python implementation to find sum of
# digits of elements at k-th level

def kLevelSumRecur(i, s, k, level):

    if s[i[0]] == '(':
        i[0] += 1

    # Find the value of current node.
    val = 0
    while i[0] < len(s) and s[i[0]] != '(' and s[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 = val if level == k else 0

    left, right = 0, 0

    # If left subtree exists
    if i[0] < len(s) and s[i[0]] == '(':
        left = kLevelSumRecur(i, s, k, level + 1)

    # if right subtree exists
    if i[0] < len(s) and s[i[0]] == '(':
        right = kLevelSumRecur(i, s, k, level + 1)

    # To take care of closing parenthesis
    i[0] += 1

    return val + left + right

# Function to find sum of digits
# of elements at k-th level
def kLevelSum(s, k):
    i = [0]
    return kLevelSumRecur(i, s, k, 0)

if __name__ == "__main__":
    s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"
    k = 2
    print(kLevelSum(s, k))
C#
// C# implementation to find sum of
// digits of elements at k-th level
using System;

class GfG {

    static int kLevelSumRecur(ref int i, 
                              string s, int k, int level) {

        if (s[i] == '(') i++;

        // Find the value of current node.
        int val = 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;

        int left = 0, right = 0;

        // If left subtree exists
        if (i < s.Length && s[i] == '(') {
            left = kLevelSumRecur(ref i, s, k, level + 1);
        }

        // if right subtree exists
        if (i < s.Length && s[i] == '(') {
            right = kLevelSumRecur(ref i, s, k, level + 1);
        }

        // To take care of closing parenthesis
        i++;

        return val + left + right;
    }

    // Function to find sum of digits
    // of elements at k-th level
    static int kLevelSum(string s, int k) {
        int i = 0;
        return kLevelSumRecur(ref i, s, k, 0);
    }

    static void Main(string[] args) {
        string s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
        int k = 2;
        Console.WriteLine(kLevelSum(s, k));
    }
}
JavaScript
// JavaScript implementation to find sum of
// digits of elements at k-th level

function kLevelSumRecur(i, s, k, level) {

    if (s[i[0]] === '(') i[0]++;

    // Find the value of current node.
    let val = 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;

    let left = 0, right = 0;

    // If left subtree exists
    if (i[0] < s.length && s[i[0]] === '(') {
        left = kLevelSumRecur(i, s, k, level + 1);
    }

    // if right subtree exists
    if (i[0] < s.length && s[i[0]] === '(') {
        right = kLevelSumRecur(i, s, k, level + 1);
    }

    // To take care of closing parenthesis
    i[0]++;

    return val + left + right;
}

// Function to find sum of digits
// of elements at k-th level
function kLevelSum(s, k) {
    let i = [0];
    return kLevelSumRecur(i, s, k, 0);
}

const s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
const k = 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:

  1. Initialize two variables,say level = -1 and sum = 0
  2. 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.
  3. 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>
using namespace std;

// Function to find sum of digits
// of elements at k-th level
int kLevelSum(string s, int k) {
    int level = -1;
    int sum = 0; 
    int n = s.length();

    for (int i=0; i<n; i++) {
        
        // increasing level number
        if (s[i] == '(')
            level++;

        // decreasing level number
        else if (s[i] == ')')
            level--;
        
        // check if current level is
        // the desired level or not
        else if (level == k) {
            int val = 0; 
            
            // find the value of node
            while (i<n && s[i]!='(' && s[i]!=')') {
                val = val*10 + (s[i]-'0');
                i++;
            }
            i--;
            sum += val;
        }
    }

    return sum;
}

int main() {
    string s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
    int k = 2;
    cout << kLevelSum(s, k);
    return 0;
}
Java
// Java implementation to find sum of
// digits of elements at k-th level
import java.util.*;

class GfG {

    // Function to find sum of digits
    // of elements at k-th level
    static int kLevelSum(String s, int k) {
        int level = -1;
        int sum = 0; 
        int n = s.length();

        for (int i = 0; i < n; i++) {

            // increasing level number
            if (s.charAt(i) == '(')
                level++;

            // decreasing level number
            else if (s.charAt(i) == ')')
                level--;

            // check if current level is
            // the desired level or not
            else if (level == k) {
                int val = 0;

                // find the value of node
                while (i < n && s.charAt(i) != '(' && s.charAt(i) != ')') {
                    val = val * 10 + (s.charAt(i) - '0');
                    i++;
                }
                i--;
                sum += val;
            }
        }

        return sum;
    }

    public static void main(String[] args) {
        String s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
        int k = 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 level
def kLevelSum(s, k):
    level = -1
    sum = 0
    n = len(s)
    i = 0
    
    while i<n:

        # increasing level number
        if s[i] == '(':
            level += 1

        # decreasing level number
        elif s[i] == ')':
            level -= 1

        # check if current level is
        # the desired level or not
        elif level == k:
            val = 0

            # find the value of node
            while i < n and s[i] != '(' and s[i] != ')':
                val = val * 10 + (ord(s[i]) - ord('0'))
                i += 1
            i -= 1
            sum += val
        
        i+=1

    return sum

if __name__ == "__main__":
    s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"
    k = 2
    print(kLevelSum(s, k))
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 kLevelSum(string s, int k) {
        int level = -1;
        int sum = 0;
        int n = s.Length;

        for (int i = 0; i < n; i++) {

            // increasing level number
            if (s[i] == '(')
                level++;

            // decreasing level number
            else if (s[i] == ')')
                level--;

            // check if current level is
            // the desired level or not
            else if (level == k) {
                int val = 0;

                // find the value of node
                while (i < n && s[i] != '(' && s[i] != ')') {
                    val = val * 10 + (s[i] - '0');
                    i++;
                }
                i--;
                sum += val;
            }
        }

        return sum;
    }

    static void Main(string[] args) {
        string s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
        int k = 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 level
function kLevelSum(s, k) {
    let level = -1;
    let sum = 0;
    let n = s.length;

    for (let i = 0; i < n; i++) {

        // increasing level number
        if (s[i] === '(')
            level++;

        // decreasing level number
        else if (s[i] === ')')
            level--;

        // check if current level is
        // the desired level or not
        else if (level === k) {
            let val = 0;

            // find the value of node
            while (i < n && s[i] !== '(' && s[i] !== ')') {
                val = val * 10 + (s.charCodeAt(i) - '0'.charCodeAt(0));
                i++;
            }
            i--;
            sum += val;
        }
    }

    return sum;
}

const s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
const k = 2;
console.log(kLevelSum(s, k));

Output
14


Next Article
Article Tags :
Practice Tags :

Similar Reads