Tree: Height of a Binary Tree

  • + 0 comments

    Full solution can be found at clormor/hacker-rank-solutions.

    It's perhaps a little confusing / unclear that a tree with a "root" of null is considered as being of depth -1. However note the following:

    1. Whilst intuitively you might think to return 0 at this point, the height of a null tree is definitely NOT 0! A tree of height 0 is a tree with a single (i.e. root) node.
    2. The constraints specify that the number of nodes is >= 1. The tree will always have a depth >= 0. This means that the only null case you need to code for is the case where you traverse to the end of the tree. Without this constraint, the author would have had to specify how to handle the special case of a "null tree".

    With that in mind, returning -1 when you encounter null makes sense - you have in effect gone "beyond" the bounds of the tree. Decrementing the height accounts for this.

    My (Java) solution:

    public static int height(Node node) {
        if (node == null) {
            // a null node is not part of the tree, so discount it
            return -1;
        } else {
            // search recursively, increment depth by 1
            return Math.max(height(node.left)+1, height(node.right)+1);
        }
    }
    

    I modified the name of the Node parameter from root to node to make it easier for the reader to understand - this function is called recursively from any point on the tree, not just the root.