I have been set the task to search and find the height of a binary search tree. In trying to resolve the issue I came up with the following solution.
static int countL = 0 ;
static int countR = 0 ;
public static int getHeight(Node root) {
if (root.left != null) {
countL++;
getHeight(root.left);
}
if (root.right != null) {
countR++;
getHeight(root.right);
}
count = Math.max(countL, countR);
return count;
}
Not the most elegant but never the less it resolves the problem for certain trees. Searching the web I have found an alternative solution. Apart from being more elegant code, what is the difference between what I have above to what can be seen below? In the quest of becoming a more proficient coder what is the best way to reduce the lines of code. My quest is to understand where i went wrong and what the code below does different in comparison to mine
private static int getHeight(Node root){
int heightLeft = 0;
int heightRight = 0;
if (root.left != null) {
heightLeft = getHeight(root.left) + 1;
}
if (root.right != null) {
heightRight = getHeight(root.right) + 1;
}
return (heightLeft > heightRight ? heightLeft : heightRight);
}