Given a binary tree represented as a string in the format node(left-subtree)(right-subtree), and an integer k, find the sum of the values of all nodes present at the k-th level of the tree. The root node is at level 0.
Note: If no node exists at level k, return 0.
Examples:
Input: s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))", k = 2 Output: 14 Explanation: The tree representation is shown below:
The sum of nodes at the 2nd level is 6 + 4 + 1 + 3 = 14.
Input: s = "(4(8()9())", k = 1 Output: 17 Explanation: The tree representation is shown below:
[Naive Approach] Using Binary Tree Construction and Level Order Traversal - O(n) Time and O(n) Space
The idea is to first construct the binary tree from its string representation and then perform a level order traversal to find the sum of nodes at level k. Since the tree is explicitly built, traversing it level by level becomes straightforward.
Working of Approach:
Parse the string recursively to construct the binary tree.
Start a level order traversal from the root using a queue.
Traverse the tree level by level while keeping track of the current level.
When the current level becomes equal to k, sum the values of all nodes at that level.
Return the computed sum. If level k does not exist, return 0.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};Node*buildTree(string&s,int&idx){if(idx>=s.size())returnnullptr;// Skip the opening parenthesis of the current subtreeif(s[idx]=='(')idx++;// Empty subtree represented as ()if(idx<s.size()&&s[idx]==')'){idx++;returnnullptr;}boolneg=false;if(s[idx]=='-'){neg=true;idx++;}intnum=0;while(idx<s.size()&&isdigit(s[idx])){num=num*10+(s[idx]-'0');idx++;}Node*root=newNode(neg?-num:num);// Recursively construct the left and right subtreesroot->left=buildTree(s,idx);root->right=buildTree(s,idx);if(idx<s.size()&&s[idx]==')')idx++;returnroot;}intkLevelSum(string&tree,intk){intidx=0;Node*root=buildTree(tree,idx);if(!root)return0;queue<Node*>q;q.push(root);intlevel=0;while(!q.empty()){intsz=q.size();// Sum all nodes when the required level is reachedif(level==k){intsum=0;while(sz--){sum+=q.front()->data;q.pop();}returnsum;}while(sz--){Node*curr=q.front();q.pop();if(curr->left)q.push(curr->left);if(curr->right)q.push(curr->right);}level++;}return0;}intmain(){stringtree="(0(5(6()())(4()(9())))(7(1()())(3()())))";intk=2;cout<<kLevelSum(tree,k);return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;classGFG{staticclassNode{intdata;Nodeleft,right;Node(intdata){this.data=data;left=right=null;}}staticNodebuildTree(Strings,int[]idx){if(idx[0]>=s.length())returnnull;// Skip the opening parenthesis of the current subtreeif(s.charAt(idx[0])=='(')idx[0]++;// Empty subtree represented as ()if(idx[0]<s.length()&&s.charAt(idx[0])==')'){idx[0]++;returnnull;}booleanneg=false;if(s.charAt(idx[0])=='-'){neg=true;idx[0]++;}intnum=0;while(idx[0]<s.length()&&Character.isDigit(s.charAt(idx[0]))){num=num*10+(s.charAt(idx[0])-'0');idx[0]++;}Noderoot=newNode(neg?-num:num);// Recursively construct the left and right subtreesroot.left=buildTree(s,idx);root.right=buildTree(s,idx);if(idx[0]<s.length()&&s.charAt(idx[0])==')')idx[0]++;returnroot;}staticintkLevelSum(Stringtree,intk){int[]idx={0};Noderoot=buildTree(tree,idx);if(root==null)return0;Queue<Node>q=newLinkedList<>();q.offer(root);intlevel=0;while(!q.isEmpty()){intsize=q.size();// Sum all nodes when the required level is reachedif(level==k){intsum=0;while(size-->0)sum+=q.poll().data;returnsum;}while(size-->0){Nodecurr=q.poll();if(curr.left!=null)q.offer(curr.left);if(curr.right!=null)q.offer(curr.right);}level++;}return0;}publicstaticvoidmain(String[]args){Stringtree="(0(5(6()())(4()(9())))(7(1()())(3()())))";intk=2;System.out.println(kLevelSum(tree,k));}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=NonedefbuildTree(s,idx):ifidx[0]>=len(s):returnNone# Skip the opening parenthesis of the current subtreeifs[idx[0]]=='(':idx[0]+=1# Empty subtree represented as ()ifidx[0]<len(s)ands[idx[0]]==')':idx[0]+=1returnNoneneg=Falseifs[idx[0]]=='-':neg=Trueidx[0]+=1num=0whileidx[0]<len(s)ands[idx[0]].isdigit():num=num*10+int(s[idx[0]])idx[0]+=1root=Node(-numifnegelsenum)# Recursively construct the left and right subtreesroot.left=buildTree(s,idx)root.right=buildTree(s,idx)ifidx[0]<len(s)ands[idx[0]]==')':idx[0]+=1returnrootdefkLevelSum(tree,k):idx=[0]root=buildTree(tree,idx)ifrootisNone:return0q=deque([root])level=0whileq:size=len(q)# Sum all nodes when the required level is reachediflevel==k:total=0for_inrange(size):total+=q.popleft().datareturntotalfor_inrange(size):curr=q.popleft()ifcurr.left:q.append(curr.left)ifcurr.right:q.append(curr.right)level+=1return0if__name__=="__main__":tree="(0(5(6()())(4()(9())))(7(1()())(3()())))"k=2print(kLevelSum(tree,k))
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intdata){this.data=data;left=right=null;}}classGFG{staticNodebuildTree(strings,refintidx){if(idx>=s.Length)returnnull;// Skip the opening parenthesis of the current subtreeif(s[idx]=='(')idx++;// Empty subtree represented as ()if(idx<s.Length&&s[idx]==')'){idx++;returnnull;}boolneg=false;if(s[idx]=='-'){neg=true;idx++;}intnum=0;while(idx<s.Length&&char.IsDigit(s[idx])){num=num*10+(s[idx]-'0');idx++;}Noderoot=newNode(neg?-num:num);// Recursively construct the left and right subtreesroot.left=buildTree(s,refidx);root.right=buildTree(s,refidx);if(idx<s.Length&&s[idx]==')')idx++;returnroot;}staticintkLevelSum(stringtree,intk){intidx=0;Noderoot=buildTree(tree,refidx);if(root==null)return0;Queue<Node>q=newQueue<Node>();q.Enqueue(root);intlevel=0;while(q.Count>0){intsize=q.Count;// Sum all nodes when the required level is reachedif(level==k){intsum=0;while(size-->0)sum+=q.Dequeue().data;returnsum;}while(size-->0){Nodecurr=q.Dequeue();if(curr.left!=null)q.Enqueue(curr.left);if(curr.right!=null)q.Enqueue(curr.right);}level++;}return0;}staticvoidMain(){stringtree="(0(5(6()())(4()(9())))(7(1()())(3()())))";intk=2;Console.WriteLine(kLevelSum(tree,k));}}
JavaScript
classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}functionbuildTree(s,idx){if(idx.value>=s.length)returnnull;// Skip the opening parenthesis of the current subtreeif(s[idx.value]==='(')idx.value++;// Empty subtree represented as ()if(idx.value<s.length&&s[idx.value]===')'){idx.value++;returnnull;}letneg=false;if(s[idx.value]==='-'){neg=true;idx.value++;}letnum=0;while(idx.value<s.length&&/\d/.test(s[idx.value])){num=num*10+Number(s[idx.value]);idx.value++;}letroot=newNode(neg?-num:num);// Recursively construct the left and right subtreesroot.left=buildTree(s,idx);root.right=buildTree(s,idx);if(idx.value<s.length&&s[idx.value]===')')idx.value++;returnroot;}functionkLevelSum(tree,k){letidx={value:0};letroot=buildTree(tree,idx);if(root===null)return0;letq=[root];letlevel=0;while(q.length>0){letsize=q.length;// Sum all nodes when the required level is reachedif(level===k){letsum=0;while(size--){sum+=q.shift().data;}returnsum;}while(size--){letcurr=q.shift();if(curr.left)q.push(curr.left);if(curr.right)q.push(curr.right);}level++;}return0;}lettree="(0(5(6()())(4()(9())))(7(1()())(3()())))";letk=2;console.log(kLevelSum(tree,k));
Output
14
[Expected Approach] Using Iterative String Traversal - O(n) Time and O(1) Space
The idea is to traverse the string directly without constructing the binary tree. While scanning the string, we keep track of the current level by updating it whenever an opening or closing parenthesis is encountered. Whenever the traversal reaches level k, the corresponding node value is parsed and added to the answer.
Working of Approach:
Initialize the current level as -1 and the answer as 0.
Traverse the string from left to right.
Increment the current level when '(' is encountered and decrement it when ')' is encountered.
Whenever the current level is equal to k and a node value is encountered, parse the complete number and add it to the answer.
Continue traversing the string until all characters are processed, then return the computed sum.
C++
#include<bits/stdc++.h>usingnamespacestd;intkLevelSum(string&s,intk){intlevel=-1;intsum=0;for(inti=0;i<s.size();){// Update the current level based on parenthesesif(s[i]=='('){level++;i++;}elseif(s[i]==')'){level--;i++;}else{boolneg=false;if(s[i]=='-'){neg=true;i++;}intnum=0;// Parse the complete node valuewhile(i<s.size()&&isdigit(s[i])){num=num*10+(s[i]-'0');i++;}if(level==k)sum+=neg?-num:num;}}returnsum;}intmain(){stringtree="(0(5(6()())(4()(9())))(7(1()())(3()())))";intk=2;cout<<kLevelSum(tree,k);return0;}
Java
classGFG{staticintkLevelSum(Strings,intk){intlevel=-1;intsum=0;for(inti=0;i<s.length();){// Update the current level based on parenthesesif(s.charAt(i)=='('){level++;i++;}elseif(s.charAt(i)==')'){level--;i++;}else{booleanneg=false;if(s.charAt(i)=='-'){neg=true;i++;}intnum=0;// Parse the complete node valuewhile(i<s.length()&&Character.isDigit(s.charAt(i))){num=num*10+(s.charAt(i)-'0');i++;}if(level==k)sum+=neg?-num:num;}}returnsum;}publicstaticvoidmain(String[]args){Stringtree="(0(5(6()())(4()(9())))(7(1()())(3()())))";intk=2;System.out.println(kLevelSum(tree,k));}}
Python
defkLevelSum(s,k):level=-1total=0i=0whilei<len(s):# Update the current level based on parenthesesifs[i]=='(':level+=1i+=1elifs[i]==')':level-=1i+=1else:neg=Falseifs[i]=='-':neg=Truei+=1num=0# Parse the complete node valuewhilei<len(s)ands[i].isdigit():num=num*10+int(s[i])i+=1iflevel==k:total+=-numifnegelsenumreturntotalif__name__=="__main__":tree="(0(5(6()())(4()(9())))(7(1()())(3()())))"k=2print(kLevelSum(tree,k))
C#
usingSystem;classGFG{staticintkLevelSum(strings,intk){intlevel=-1;intsum=0;for(inti=0;i<s.Length;){// Update the current level based on parenthesesif(s[i]=='('){level++;i++;}elseif(s[i]==')'){level--;i++;}else{boolneg=false;if(s[i]=='-'){neg=true;i++;}intnum=0;// Parse the complete node valuewhile(i<s.Length&&char.IsDigit(s[i])){num=num*10+(s[i]-'0');i++;}if(level==k)sum+=neg?-num:num;}}returnsum;}staticvoidMain(){stringtree="(0(5(6()())(4()(9())))(7(1()())(3()())))";intk=2;Console.WriteLine(kLevelSum(tree,k));}}
JavaScript
functionkLevelSum(s,k){letlevel=-1;letsum=0;for(leti=0;i<s.length;){// Update the current level based on parenthesesif(s[i]==='('){level++;i++;}elseif(s[i]===')'){level--;i++;}else{letneg=false;if(s[i]==='-'){neg=true;i++;}letnum=0;// Parse the complete node valuewhile(i<s.length&&/\d/.test(s[i])){num=num*10+Number(s[i]);i++;}if(level===k)sum+=neg?-num:num;}}returnsum;}// Driver Codelettree="(0(5(6()())(4()(9())))(7(1()())(3()())))";letk=2;console.log(kLevelSum(tree,k));