reduce time complexity O(n²) to O(n)

the solution can be optimized by calculating the height in the same recursion  rather than calling a height() function separately.