forked from Ritikraja07/Java-problem-Open-Source
-
Notifications
You must be signed in to change notification settings - Fork 1
/
FindTotalNumberOfNodesInBST
58 lines (48 loc) · 1.05 KB
/
FindTotalNumberOfNodesInBST
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
// Java program for the above approach
import java.io.*;
class GFG {
// tree node
static class node
{
public int data;
public node left, right;
public node(){
data = 0;
left = right = null;
}
}
// Function to get the count of nodes
// in complete binary tree
static int totalNodes(node root)
{
if (root == null)
return 0;
int l = totalNodes(root.left);
int r = totalNodes(root.right);
return 1 + l + r;
}
// Helper function to allocate a new node
// with the given data
static node newNode(int data)
{
node temp = new node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Driver Code
public static void main(String args[])
{
node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(9);
root.right.right = newNode(8);
root.left.left.left = newNode(6);
root.left.left.right = newNode(7);
System.out.println(totalNodes(root));
}
}
// This code is contributed by poojaagarwal2.