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.
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.
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.
2
1 2 3 4 -1 -1 5 -1 -1 -1 -1
2
1 2 3 4 -1 -1 5 -1 -1 -1 -1
3
5
9
For the first test case, the nodes at level 2 are 2 and 3; therefore, their sum will be our answer. 2 + 3 = 5. Therefore the final answer is 5.
For the second test case, the nodes at level 3 are 4 and 5; therefore, their sum will be our answer. 4 + 5 = 9. Therefore the final answer is 9.
2
9 10 11 -1 -1 -1 -1
1
9 10 11 -1 -1 -1 -1
2
9
21
Will inorder traversal help?
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 do this for all the nodes at Kth level.
The steps are as follows:
O(N), where ‘N’ is the number of nodes in the binary tree.
We are traversing the whole binary once. Hence, the overall time complexity is O(N).
O(N), where ‘N’ is the number of nodes in the binary tree.
We are traversing the whole binary once. Hence, the overall recursive stack made will be equal to the height of the tree. Hence space complexity is O(N).