2011-05-04 102 views
0

可能重複:
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)); 
} 

回答