不平衡的二叉树

时间:2011-05-04 08:42:28

标签: tree binary-tree binary-search

  

可能重复:
  How to determine if binary tree is balanced?

任何人都可以告诉我如何在算法上检查二叉树是否不平衡?

编辑:以下是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));
}

1 个答案:

答案 0 :(得分:1)