Monday, April 23, 2018

Height of a binary tree

Height of a binary tree is 1+ number of edges between root node and a leaf node at longest distance from root node. Descendants of a node is one level deeper than that node. In other words, we need to find out distance from root node to deepest leaf node. Height of empty tree is 0. Height of tree in following tree is 4.

Ways to find out height:

1. Modified level order traversal: We can modify the level order traversal, where we are not just visiting the nodes level by level but we also keep track of level boundary. Total number of levels will be height of the tree.

2. Recursive method: 
In this method, we traverse the tree from root towards leaf recursively. We maintain a counter and increase the counter every time we move one level down. Final count is the height of the tree. Following the java solution for this. Height of the tree in this program is 5:

public class Height {
    public static void main(String[] args) throws Exception {
        //Build Tree        
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        Node node7 = new Node(7);
        Node node8 = new Node(8);
        Node node9 = new Node(9);
        Node node10 = new Node(10);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        node4.left = node8;
        node7.right = node9;
        node9.left = node10;
        System.out.println(height(node1));
    }

    private static int height(Node root){
        if(root != null){
            return 1 + max(height(root.left), height(root.right));
        }

        return 0;
    }

    private static int max(int left, int right){
        if(left > right){
            return left;
        }

        return right;
    }
    static class Node {
        int data;
        Node left;
        Node right;

        Node(int data) {
            this.data = data;
        }
    }

}

No comments:

Post a Comment

Categories