Sum At Kth Level

You are given a ‘root’ of the binary tree, and you have to return the sum of all nodes present at the Kth level from the top. The root node is considered as level 1, and below it is level 2, and so on.

Note:

A binary tree is a tree in which each node has at most 2 children.
Example:
For Example, the root node is given as follows :
‘ROOT’ = 1 2 3 4 -1 -1 5 -1 -1 -1 -1 and ‘K’ = 2, Then the sum of all nodes at K-level will be 5. This is because 2 and 3 are present at level 2 and 2 + 3 = 5. Therefore 5 is the answer.
Input Format:
The first line of input contains a single integer ‘T’, representing the number of test cases or queries to be run. 

The first line of each test case contains elements in the level order form. The line consists of values of nodes separated by a single space. In case a node is null, we take -1 in its place.

The second line of each test case contains a single integer ‘K’, which denotes the level.
Constraints:
1 <= ‘T’ <= 10
1 <= ‘N’ <= 1000
0 <= data <= 10^3
0 <= ‘K’ <= ‘N’

Time Limit: 1 sec.
Output Format :
For every test case, print a single line that contains a single integer which denotes the sum of all nodes at the Kth level.

The output of each test case is printed in a separate line.

Note:

You don’t have to print anything, it has already been taken care of. Just implement the function. 
CodingNinjas
author
2y
Inorder Traversal.

The idea is to do an inorder traversal of the tree, and at each level, we go down, reduce K by 1, and all the states where K = 1, add that node's value in our answer, and recursively...read more

CodingNinjas
author
2y
Level Order Traversal

The idea is to use level order traversal and add all nodes at the Kth level.

The steps are as follows:

  • Maintain a queue, ‘que’ to do a level order traversal, and maintain a variabl...read more
Help your peers!
Add answer anonymously...
Accenture Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter