Binary tree is a data structure which a root and nodes. Here, a root is like a parent. Nodes are like children. It has a structure of root, left child and right child.
Let us count the number of nodes in a binary tree. Binary tree
has two nodes in all levels.
Program implementation:
- · Create a node with data and left child and right child.
- · Initialise the values.
- · Create a binary tree class. Declare a variable for root.
- · A function is defined to count the nodes.
- · Using a recursive function, count it.
- · Let us invoke the main() function, to initialise the objects.
- · Use the objects to call the function.
- · Print the number of nodes in the output screen.
Classes incuded:
Node: It defines the structureof node.
BinaryTreeEg : It defines the structure of binary tree.
Variables:
‘data’ , ‘value’, ‘c_left’,’c_right’
Functions:
‘countIt()’ – This function counts the number of nodes.
‘main()’ – It creates the objects and calls the function to
get the output.
Program:
class Node {
int data;
Node c_left,
c_right;
Node(int value) {
data = value;
c_left =
c_right = null;
}
}
class BinaryTreeEg {
Node root;
// countIt method
to count the nodes in the binary tree
public int
countIt(Node node) {
if (node ==
null) {
return 0;
}
// A recursive
function to count the nodes
return 1 +
countIt(node.c_left) + countIt(node.c_right);
}
public static void
main(String[] args) {
BinaryTreeEg
bt = new BinaryTreeEg();
// Creating a
sample binary tree
bt.root = new
Node(10);
bt.root.c_left
= new Node(20);
bt.root.c_right = new Node(30);
bt.root.c_left.c_left = new Node(40);
bt.root.c_left.c_right = new Node(50);
bt.root.c_right.c_left = new Node(60);
bt.root.c_right.c_right = new Node(70);
System.out.println("Number of nodes in the binary tree: " +
bt.countIt(bt.root));
}
}
Output:
Compile and run the program to get the output.
C:\raji\blog>javac BinaryTreeEg.java
C:\raji\blog>java BinaryTreeEg
Number of nodes in the binary tree: 7
That’s all. The java program to count the number of nodes in
a binary tree was implemented successfully. Hope this code is useful to you.
Happy coding!!
No comments:
Post a Comment