Given a binary tree having ‘N’ number of nodes. Your task is to find the sum of all left nodes present in the input binary tree. That is, you need to take the sum of all nodes which are the left child of some node.
Note :
1. A binary tree is a tree in which each node can have at most two children.
2. The given tree will be non-empty i.e the number of non-NULL nodes will always be greater than or equal to 1.
3. Multiple nodes in the tree can have the same values, all values in the tree will be positive.
Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line of input contains an integer ‘T’, which denotes the number of test cases. Then each test case follows.
The first line of every test case contains elements of the Binary Tree in the level order form. The input consists of values of nodes separated by a single space in a single line. In case a node is null, we take -1 in its place.
For Example :
Consider the binary tree:
The input for the tree depicted in the above image would be :
3
5 1
6 2 0 8
-1 -1 7 4 -1 -1 -1 -1
-1 -1 -1 -1
Explanation :
Level 1 :
The root node of the tree is 3
Level 2 :
Left child of 3 = 5
Right child of 3 = 1
Level 3 :
Left child of 5 = 6
Right child of 5 = 2
Left child of 1 = 0
Right child of 1 = 8
Level 4 :
Left child of 6 = null (-1)
Right child of 6 = null(-1)
Left child of 2 = 7
Right child of 2 = 4
Left child of 0 = null (-1)
Right child of 0 = null (-1)
Left child of 8 = null (-1)
Right child of 8 = null (-1)
Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)
Left child of 4 = null (-1)
Right child of 4 = null (-1)
The first not-null node (of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.
The input ends when all nodes at the last level are null (-1).
Output format :
For each test case, print the sum of all left nodes present in the binary tree
The output of each test case should be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Sample Input 1 :
2
3 5 1 6 2 0 8 -1 -1 7 4 -1 -1 -1 -1 -1 -1 -1 -1
1 2 3 4 5 -1 -1 6 -1 -1 -1 -1 -1
Sample Output 1 :
18
12
Explanation for Sample Input 1 :
Test Case 1 :
The nodes 5, 6, 7, and 0 are the only nodes that were the left child of any other node. S, they sum up to make the sum 18.
Test Case 2 :
The nodes 2, 4, and 6 are the only nodes that were the left child of any other node. S, they sum up to make the sum 12.
Sample Input 2 :
2
5 2 3 8 1 -1 -1 7 9 -1 -1 5 6 -1 -1 -1 -1 -1 -1
1 5 7 -1 -1 6 3 9 8 -1 -1 -1 -1 13 -1 -1 -1
Sample Output 2 :
22
33