Algorithm to calculate height of a binary tree

Binary tree is a data structure of tree shape in which each node can have either 2 or 0 children(s). Height of a tree is the maximum depth of nodes of the tree. Here is the algorithm to that returns the height of the tree. It should be called by passing position of root node of tree as argument.

Algorithm getHeight(pos)
     Input position pos of the node whose height is to be found out
     If (isInternal(pos))
             X = getHeight(leftchild(pos))
             Y = getHeight(rightchild(pos))
             Return greater(X,Y) + 1
 Return 0

The method names used above are

isInternal(pos) - Returns true if the position pos is internal

leftchild(pos) – Returns the position of the left child of the pos

rightchild(pos) – Returns the position of the right child of the pos

geater(X,Y) – Returns greater of X and Y.

At each node, the recursive algorithm will accumulate height of left and right sub tree and pass it to parent by adding 1 to the greater one. However, if the node is external it will simply return 0 to parent. This is how the algorithm works.

Leave a comment

Your comment