JAVA program to find height of a node in a binary tree

Posted On // Leave a Comment

CODE:

import java.util.Scanner;

public class nodeHeight{
    static int height,nod;
    static void traverse(node tree,int currHeight){
        if(tree==null)
            return;
        if(tree.data==nod){
            height=currHeight+1;
            return;
        }
        if(height == -1){
            traverse(tree.left,currHeight+1);
            traverse(tree.right,currHeight+1);
        }
    }

    static Scanner in = new Scanner(System.in);

    static node inputTree(){
        node temp=new node();
        System.out.print("Enter the value: ");
        temp.data=in.nextInt();
        System.out.print("Enter y if the node "+temp.data+" has left subtree: ");
        if(in.next().charAt(0)=='y')
            temp.left=inputTree();
        else
            temp.left=null;
        System.out.print("Enter y if the node "+temp.data+" has right subtree: ");
        if(in.next().charAt(0)=='y')
            temp.right=inputTree();
        else
            temp.right=null;
        return temp;
    }

    public static void main(String[] args) {
        node tree = new node();
        System.out.println("Enter tree:");
        tree = inputTree();
        height = -1;
        System.out.print("Enter node:");
        nod=in.nextInt();
        traverse(tree,0);
        if(height==-1)
            System.out.println("Node not found");
        else
            System.out.print("Node is at height "+height);
    }
}

OUTPUT:

Enter tree:
Enter the value: 5
Enter y if the node 5 has left subtree: y
Enter the value: 2
Enter y if the node 2 has left subtree: y
Enter the value: 1
Enter y if the node 1 has left subtree: n
Enter y if the node 1 has right subtree: n
Enter y if the node 2 has right subtree: y
Enter the value: 3
Enter y if the node 3 has left subtree: n
Enter y if the node 3 has right subtree: y
Enter the value: 4
Enter y if the node 4 has left subtree: n
Enter y if the node 4 has right subtree: n
Enter y if the node 5 has right subtree: y
Enter the value: 6
Enter y if the node 6 has left subtree: n
Enter y if the node 6 has right subtree: n
Enter node:1
Node is at height 3

NOT SURE WITH THE CODE PLS INFRM IF THERE ARE ANY TESTCASES IN WHICH THE CODE FAILS

0 comments :

Post a Comment