判断一颗二叉树树是否为AVL树

1)先判断该树是否为二叉排序树,也可以采用中序遍历该树,判断是否有序

2)判断该树是否为平衡树

代码如下:

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;
}

转载地址:http://www.cnblogs.com/newpanderking/p/3969557.html

    原文作者:AVL树
    原文地址: https://blog.csdn.net/pegasus10/article/details/39494847
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞