In this article I will provide a solution to the Tree Height sample Codility problem. The problem description is copyrighted, so have a look at the link for the description. The problem itself is quite easy, but I’ll still include it here for the sake of completeness of having solutions to all problems for which Codility does not post a solution. The gist of the problem is as follows:

Given a binary tree, its height is the length of the longest possible path from the root to a leaf. Calculate the height of a binary tree.

Since the Codility problem restrictions are small, the simplest recursive solution comes to mind since under these restrictions we will not run out of stack space. The idea is as follows: Recursively compute the height of the left and right subtrees; then, the answer is just the maximum of the height of the left and right subtree.

The 100/100 code in Java: