Sum of nodes at k-th level in a tree represented as string
Last Updated :
14 Oct, 2024
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-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));
[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>
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));
Similar Reads
Binary Tree Data Structure A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and
3 min read
Introduction to Binary Tree Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Introduction to Binary TreeRepresentation of Bina
15+ min read
Properties of Binary Tree This post explores the fundamental properties of a binary tree, covering its structure, characteristics, and key relationships between nodes, edges, height, and levelsBinary tree representationNote: Height of root node is considered as 0. Properties of Binary Trees1. Maximum Nodes at Level 'l'A bina
4 min read
Applications, Advantages and Disadvantages of Binary Tree A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Applications:General ApplicationsDOM in HTML: Binary trees help manage the hierarchical structure of web
2 min read
Binary Tree (Array implementation) Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
6 min read
Maximum Depth of Binary Tree Given a binary tree, the task is to find the maximum depth of the tree. The maximum depth or height of the tree is the number of edges in the tree from the root to the deepest node.Examples:Input: Output: 2Explanation: The longest path from the root (node 12) goes through node 8 to node 5, which has
11 min read
Insertion in a Binary Tree in level order Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner.Examples:Input: key = 12 Output: Explanation: Node with value 12 is inserted into the binary tree at the first position available in level order manner.Approach:The
8 min read
Deletion in a Binary Tree Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with t
12 min read
Enumeration of Binary Trees A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. Below two are considered same unlabelled trees o o / \ / \ o o o o Below two are considered different labelled trees A C / \ / \ B C A B How many different Unlabelled Binar
3 min read
Types of Binary Tree