I was writing this code to check if a tree is balanced or not and I ran into a situation where I would have liked the method to return 2 values at each step. First to signify whether the tree is balanced at that level or not, and second to return the height at the level so that I can use it to check the balanced nature of the parent. I ended up writing the method such that it returns -1 if the tree is not balanced and the actual height if the tree is balanced at that level.
Is there a better way to do it? If not, then I think I should at least have a better name for the method getHeight
. Can you review my code as a whole and let me know my shortcomings?
public boolean isBalanced(Node root){
return getHeight(root)!=-1;
}
private int getHeight(Node node){
if(node ==null)
return 1;
int leftHeight = getHeight(node.getLeft());
int rightHeight = getHeight(node.getRight());
if(leftHeight==-1 || rightHeight ==-1)
return -1;
int diff = Math.abs(leftHeight-rightHeight);
if(diff>1)
return -1;
return Math.max(leftHeight,rightHeight) + 1;
}