判断一棵树是不是AVL树

这里的AVL树指的是,在BST树的基础上,满足任意结点的平衡因子绝对值小于2


判断主程序:

bool JudgeAvl(TreeNode *root, int min, int max, int &deepth){
    if(root == NULL) return true;
    if(root->val < min || root->val > max) return false; //用于判断是不是BST
    int left_deepth = 0, right_deepth = 0;
    if(JudgeAvl(root->left, min, root->val, left_deepth) && JudgeAvl(root->right, root->val, max, right_deepth)){
        if(abs(left_deepth - right_deepth) >= 2)   //判断平衡因子是否小于2
            return false;
        deepth = (left_deepth > right_deepth) ? (left_deepth + 1):(right_deepth + 1);  //得到当前结点的深度,一定要传引用
        return true;
    }   
    return false;
}

调用主接口:

int main(void)
{
    TreeNode *root = NULL;
    PreoderBuildTree(root);
    int tree_deepth = 0;
    if(JudgeAvl(root, INT_MIN, INT_MAX, tree_deepth))
        std::cout << "TRUE" << std::endl;
    else
        std::cout << "FALSE" << std::endl;
}


你可能感兴趣的:(二叉树各种)