Skip to content

Commit 27dd9eb

Browse files
authoredJan 2, 2023
Create Binary Trees1-Sum Of Nodes
1 parent 6d1eb10 commit 27dd9eb

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
 

‎Binary Trees1-Sum Of Nodes

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
For a given Binary Tree of integers, find and return the sum of all the nodes data.
2+
Example:
3+
10
4+
/ \
5+
20 30
6+
/ \
7+
40 50
8+
9+
When we sum up all the nodes data together, [10, 20, 30, 40 50] we get 150. Hence, the output will be 150.
10+
Input Format:
11+
The first and the only line of input will contain the nodes data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.
12+
Output Format:
13+
The first and the only line of output prints the sum of all the nodes data present in the binary tree.
14+
Note:
15+
You are not required to print anything explicitly. It has already been taken care of.
16+
Constraints:
17+
1 <= N <= 10^6
18+
Where N is the total number of nodes in the binary tree.
19+
20+
Time Limit: 1 sec
21+
Sample Input 1:
22+
2 3 4 6 -1 -1 -1 -1 -1
23+
Sample Output 1:
24+
15
25+
Sample Input 2:
26+
1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1
27+
Sample Output 2:
28+
28
29+
30+
*******************************************Code*******************************************
31+
32+
public static int getSum(BinaryTreeNode<Integer> root) {
33+
34+
if(root == null) {
35+
return 0;
36+
}
37+
int leftSum = getSum(root.left);
38+
int rightSum = getSum(root.right);
39+
return leftSum + rightSum + root.data;
40+
}

0 commit comments

Comments
 (0)
Please sign in to comment.