Hi!
I have a problem with a binary tree programing (AVL)where I have to check if it is or if it isn't balanced....
I have made a start but I know it isn't right...
public boolean isBalanced() {
boolean balanced = true;
isBalanced(root, balanced);
return balanced;
}
private void isBalanced(BinaryNode<T> node, boolean balanced) {
if(balanced)
{
int balanceFactor = getBalanceFactor(node);
if(balanceFactor == 1) { // Has children
int left = getBalanceFactor(node.left);
int right = getBalanceFactor(node.right);
int difference = Math.abs(left - right);
if(difference == 2)
balanced = false;
else {
isBalanced(node.left, balanced);
isBalanced(node.right, balanced);
}
}
}
}
private int getBalanceFactor(BinaryNode<T> node) {
if(node == null)
return -1;
else if(node.left == null && node.right == null)
return 0;
else
return 1;
}