任何人都可以告诉我如何在算法上检查二叉树是否不平衡?
编辑:以下是Java中的答案:
public int getDepth(Node n){
if(n == null){
return 0;
}
return 1 + (Math.max(getDepth(n.left), getDepth(n.right)));
}
public boolean isBalanced(Node n){
if(n == null){
return true;
}
int leftHeight = getDepth(n.left);
int rightHeight = getDepth(n.right);
return (Math.abs(leftHeight - rightHeight) <= 1 && isBalanced(n.left) && isBalanced(n.right));
}
答案 0 :(得分:1)