Que :-Write a program to count the number of nodes in a binary tree. For example if we have the following tree , then it must return 5.
Algorithm :
Visualization of above Algorithm (How it works):
If we call the count() function .Then the working of the recursive count function will be as follows :
Implementation :
Please comment if you like the above post or find any mistake .
public static int count(BSTNode p)
{
if(p==null)
{
return 0;
}
return count(p.left)+1+count(p.right);
}
Visualization of above Algorithm (How it works):
Implementation :
class BSTNode {
int data;
BSTNode
right;
BSTNode
left;
BSTNode(int d) {
data = d;
}
}
public class CountNodes {
public static void main(String args[])
{
BSTNode
root = new BSTNode(4);
root.left = new BSTNode(2);
root.right = new BSTNode(5);
root.left.left = new BSTNode(1);
root.left.right = new BSTNode(3);
int n = CountNodes(root);
System.out.println(n);
}
private static int CountNodes(BSTNode
root) {
if (root == null) {
return 0;
}
return (CountNodes(root.left) + 1 + CountNodes(root.right));
}
}
Please comment if you like the above post or find any mistake .
Look for out and about what kind of binary possessions can be found. No matter whether that suits you futures, currency trading, as well as other goods, make certain the software program that you are about to subscribe for has this.
ReplyDeleteTrade binary options on stocks and indices with EZTrader's leading platform. auto binary signals review
ReplyDelete