1. 程式人生 > >判斷二叉樹是否為平衡樹

判斷二叉樹是否為平衡樹

平衡二叉樹

給定一個二叉樹,確定它是高度平衡的。對於這個問題,一棵高度平衡的二叉樹的定義是:一棵二叉樹中每個節點的兩個子樹的深度相差不會超過1。

先求左子樹和右子樹的最大深度,然後判斷是否相差大於1,如果是,則不可能是,如果相差小於,繼續遞迴呼叫判斷左子樹和右子樹是否都是平衡二叉樹。

程式碼實現

bool isBalanced(TreeNode *root) {
        // write your code here
        if(root == NULL)
            return true;

        int leftDepth = MaxDepth(root->left);
        int
rightDepth = MaxDepth(root->right); if(abs(rightDepth - leftDepth) > 1) { return false; } else{ return isBalanced(root->left) && isBalanced(root->right); } } int MaxDepth(TreeNode *root){ if(root == NULL
) return false; int leftDepth = MaxDepth(root->left) + 1; int rightDepth = MaxDepth(root->right) + 1; return leftDepth > rightDepth ? leftDepth : rightDepth; }