tree || BST level count in java || How to count tree Level

            The tree can count , level of tree 

    
class Node{
    Node left , right;
    int data ;
    Node(int data){
        this.data=data;
        left = null;
        right = null;
    }
}
public class countlevel {
    Node root;
    public static void print(Node data){
        if (data!=null) {
            print(data.left);
            System.out.print(" "+data.data);
            print(data.right);
        }
    }
    public static int count(Node data){
        if (data==null) {
            return 0;
        }
       if (data.left==null && data.right==null) {
              return 1;
       }
       return count(data.left)+count(data.right);
    }
   public static void main(String[] args) {
       countlevel tree = new countlevel();
        tree.root = new Node(10);
        tree.root.left = new Node(5);
        tree.root.right = new Node(20);
        print(tree.root);

        int count = count(tree.root);
        System.out.println();
        System.out.println("The Level of Tree : "+count);
   }
   
}
OUTPUT:  5 10 20
The Level of Tree : 2

Comments