Design a method that determines whether or not a binary tree is fully balanced.
This method takes no parameters, and returns a boolean value: true if the tree is
fully balanced, and false if it is not.
public boolean isBalanced() {
return isBalanced(root);
}
private boolean isBalanced(Node node) {
if (node == null)
return true;
int leftHeight = height(node.left);
int rightHeight = height(node.right);
return Math.abs(leftHeight - rightHeight) <= 1 && isBalanced(node.left) && isBalanced(node.right);
}
private int height(Node node) {
return node == null ? 0 : 1 + Math.max(height(node.left), height(node.right));
}
Comments
Leave a comment