判断二叉树是否AVL树

一、算法思想:
递归法判断一个二叉树是否平衡二叉树(AVL树),可以根据它的定义写出代码:(1)空树是一个AVL树;(2)只有一个根结点的树是一个AVL树;(2)左子树是一颗AVL树,且右子树是一个AVL树,且左子树的高度与右子树的高度差绝对值不超过1。

二、代码:

/* name: author:followStep description: date:2018/3/17 11:06:15 */

//#define LOCALE
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <iostream>
using namespace std;

struct bnode{
    int data;
    bnode *lchild, *rchild;
};
typedef bnode *btree;

int get_deep(btree bt)
{
    if(bt == NULL)
        return 0;
    else if(bt->lchild == NULL && bt->rchild == NULL)
        return 1;
    else{
        int d1, d2;
        d1 = get_deep(bt->lchild);
        d2 = get_deep(bt->rchild);
        return d1 > d2 ? 1+d1 : 1+d2;
    }
}

bool is_avl(btree bt)
{
    if(bt == NULL)
        return true;
    else if(bt->lchild == NULL && bt->rchild == NULL)
        return true;
    else
        return is_avl(bt->lchild) && is_avl(bt->rchild) && 
            fabs(get_deep(bt->lchild)-get_deep(bt->rchild)) <= 1;
}

void init_btree(btree &bt)
{
    bt = (btree)malloc(sizeof(bnode));
    bt->lchild = bt->rchild = NULL;
}

bnode *new_bnode()
{
    bnode *bn = (bnode*)malloc(sizeof(bnode));
    bn->lchild = bn->rchild = NULL;
    return bn;
}

int main()
{
#ifdef LOCALE
    freopn(".in", "r", stdin)
    freopen(".out", "w", stdout)
#endif

    btree bt;
    init_btree(bt);

    bnode *bn1, *bn2, *bn3, *bn4, *bn5;
    bn1 = new_bnode();
    bn2 = new_bnode();
    bn3 = new_bnode();
    bn4 = new_bnode();
    bn5 = new_bnode();

    bt->lchild = bn1;
    bn1->lchild = bn2;
    bn1->rchild = bn3;
    bn2->lchild = bn4;
// bn4->lchild = bn5;

    bool ans = is_avl(bt->lchild);

    cout << ans;

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