This repository has been archived by the owner on Apr 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
SumOfNodes.java
75 lines (49 loc) · 2.05 KB
/
SumOfNodes.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//-- PROGRAM TO COUNT THE NUMBER OF NODES IN A TREE USING RECURSION
//-- BINARY TREE: WHERE EACH NODE CAN ATMOST HAVE 2 CHILDREN
public class SumOfNodes{
//-- CREATING A TREE NODE CLASS
public static class TreeNode{
TreeNode leftNode, rightNode;
int data;
TreeNode(int data){
this.data = data;
leftNode = null;
rightNode = null;
}
}
//--METHOD FOR COUNTING THE NUMBER OF NODES IN A BINARY TREE
public static int totalNodes(TreeNode node){
TreeNode currentNode = node;
int counter = 1;
if(currentNode==null)
return 0;
else{
return counter + totalNodes(currentNode.leftNode) + totalNodes(currentNode.rightNode);
}
}
//-- METHOD FOR CALCULATING SUM OF ALL THE NODES OF A BINARY TREE
public static int sumOfNodes(TreeNode node){
TreeNode currentNode = node;
if(currentNode==null)
return 0;
else{
return currentNode.data + sumOfNodes(currentNode.leftNode) + sumOfNodes(currentNode.rightNode);
}
}
public static void main(String[] args){
//-- POPULATING THE BINARY TREE
TreeNode root = new TreeNode(10);
root.leftNode = new TreeNode(20);
root.rightNode = new TreeNode(30);
root.leftNode.leftNode = new TreeNode(40);
root.leftNode.rightNode = new TreeNode(50);
root.rightNode.leftNode = new TreeNode(60);
root.rightNode.rightNode = new TreeNode(70);
root.leftNode.leftNode.leftNode = new TreeNode(80);
root.leftNode.leftNode.rightNode = new TreeNode(90);
root.rightNode.rightNode.leftNode = new TreeNode(100);
root.rightNode.rightNode.rightNode = new TreeNode(110);
int value = sumOfNodes(root);
System.out.println("THE SUM OF ALL THE NODES IN THE TREE ARE: "+value);
}
}