判斷一棵二叉樹是否為AVL樹


思路:AVL樹是高度平衡的二叉搜索樹,這里為了清晰說明,分別判斷是否為搜索樹,是否為平衡樹。

struct TreeNode
{
    struct TreeNode *left;
    struct TreeNode *right;
    int key;
};
//這里先判斷是否為二叉搜索樹,其次判斷是否為平衡的
bool IsAVL(TreeNode *root,int depth)
{
    if (isBST(root)&&isBalance(root,&depth))
    return true;
    return false;
}

//判斷是否為二叉搜索樹
bool isBST(TreeNode *root)
{
    if(root == NULL)return true;
    if (!isBST(root->left))return false;
    if (!isBST(root->right))return false;
    TreeNode *cur = root->left;
    if (cur != NULL)
    {
        while(cur->right!=NULL)cur = cur->right;
        if(root->key < cur->key)return false;
    }
    TreeNode *cur = root->right;
    if (cur != NULL)
    {
        while(cur->left!=NULL)cur = cur->left;
        if(root->key > cur->key)return false;
    }
    return true;
}

//判斷是否平衡
bool isBalance(TreeNode *root,int *depth)
{
    if (root == NULL)
    {
        *depth = 0;
        return true;
    }
    int depthl,depthr;
    if(!isBalance(root->left,&depthl))return false;
    if(!isBalance(root->right,&depthr))return false;
    int diff = depthl - depthr;
    if(diff > 1 || diff < -1)return false;
    *depth = 1+(depthl>depthr?depthl:depthr);
    return true;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM