patternjavaMinor
Checking if a tree is balanced or not
Viewed 0 times
balancedcheckingtreenot
Problem
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
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;
}Solution
These functions can be static, and therefore should be. Marking them
Instead of using
I would expect
Never omit braces like that. You will contribute to a coding accident: [Citation 1] [Citation 2]. If you really want to omit braces, then put the entire conditional statement on the same line for safety.
static makes it clear that this is not object-oriented code. It also serves as a hint for the JIT to inline the helper function.Instead of using
Math.abs() and Math.max(), I suggest using Math.max() and Math.min(), which simplifies the conditionals a bit.I would expect
getHeight(null) to return 0. As you've written it, a node with no children is at height 2, which is a weird place to start counting, even if it works.Never omit braces like that. You will contribute to a coding accident: [Citation 1] [Citation 2]. If you really want to omit braces, then put the entire conditional statement on the same line for safety.
private static int getHeight(Node node) {
if (node == null) return 0;
int leftHeight = getHeight(node.getLeft()),
rightHeight = getHeight(node.getRight());
int taller = Math.max(leftHeight, rightHeight),
shorter = Math.min(leftHeight, rightHeight);
if (shorter 1) {
return -1; // Unbalanced tree
} else {
return taller + 1;
}
}Code Snippets
private static int getHeight(Node node) {
if (node == null) return 0;
int leftHeight = getHeight(node.getLeft()),
rightHeight = getHeight(node.getRight());
int taller = Math.max(leftHeight, rightHeight),
shorter = Math.min(leftHeight, rightHeight);
if (shorter < 0 || taller - shorter > 1) {
return -1; // Unbalanced tree
} else {
return taller + 1;
}
}Context
StackExchange Code Review Q#90609, answer score: 3
Revisions (0)
No revisions yet.