Sum at Level i Binary Tree
Problem :
Given a binary tree and a number i, the task is to find sum of tree nodes at level i. The Binary Tree given in string form: (node-value(left-subtree)(right-subtree))
Idea is to count opening brackets , if no. of opening bracket is == level+1 then it means now we are at level k , add this number to sum.
import java.util.*;
import java.lang.*;
import java.io.*;
class hackerranksolutionc
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=Integer.parseInt(ab.nextLine().trim());
while(t-->0)
{
int n=Integer.parseInt(ab.nextLine().trim());
String str=new String(ab.nextLine().trim());
//System.out.println(str);
int c=0,sum=0;
for(int i=0;i<str.length();++i)
{
if(str.charAt(i)=='(')
{
++c;
++i;
int val=0;
while(i<str.length() && (str.charAt(i)!=')' && str.charAt(i)!='('))
{
if(c==n+1)
{
val=val*10+str.charAt(i)-'0';
}
++i;
}
if(val!=0)
sum+=val;
//System.out.println(val+" ( fnd "+i+" ");
}
if(i<str.length() && str.charAt(i)==')')
--c;
else if(i<str.length() && str.charAt(i)=='(')
--i;
}
System.out.println(sum);
}
}
}
Given a binary tree and a number i, the task is to find sum of tree nodes at level i. The Binary Tree given in string form: (node-value(left-subtree)(right-subtree))
Idea is to count opening brackets , if no. of opening bracket is == level+1 then it means now we are at level k , add this number to sum.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class hackerranksolutionc
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=Integer.parseInt(ab.nextLine().trim());
while(t-->0)
{
int n=Integer.parseInt(ab.nextLine().trim());
String str=new String(ab.nextLine().trim());
//System.out.println(str);
int c=0,sum=0;
for(int i=0;i<str.length();++i)
{
if(str.charAt(i)=='(')
{
++c;
++i;
int val=0;
while(i<str.length() && (str.charAt(i)!=')' && str.charAt(i)!='('))
{
if(c==n+1)
{
val=val*10+str.charAt(i)-'0';
}
++i;
}
if(val!=0)
sum+=val;
//System.out.println(val+" ( fnd "+i+" ");
}
if(i<str.length() && str.charAt(i)==')')
--c;
else if(i<str.length() && str.charAt(i)=='(')
--i;
}
System.out.println(sum);
}
}
}
0 Comments:
Post a Comment