Tuesday 24 December 2013

Finding Height of a binary tree

Question :  

To find height of any binary tree

Code :


public class TreeHeightFinder {

    public static int findHeight(Node root){

        int leftHeight = 0;
        int rightHeight = 0;

        if(root.getLeft() != null){
            leftHeight = findHeight(root.getLeft());
        }
        if(root.getRight() != null){
            rightHeight = findHeight(root.getRight());
        }

        int maxHeight =  max(leftHeight,rightHeight);

        return 1 + maxHeight;

    }

    public static int max(int a,int b){

        return a > b ? a : b;

    }
} 



Now lets build a tree and test it(tree is like below)





    public static void main(String args[]){

        Node root = new Node(1);

        Node l = new Node(2);
        Node r = new Node(3);

        Node l1 = new Node(12);
        Node l2 = new Node(13);

        Node r1 = new Node(6);
        Node r2 = new Node(8);

        root.setLeft(l);
        root.setRight(r);

        l.setLeft(l1);
        l.setRight(l2);

        r.setLeft(r1);
        r.setRight(r2);

        System.out.println("Height is : " + TreeHeightFinder.findHeight(root));
    }





Output :

Height is : 3
t> UA-39527780-1 back to top