平衡二叉树判定方法(c++)实现

-- 欢迎指正--

平衡二叉树特点:

  任意一个结点的平衡因子(左子树高度 - 右子树高度)的绝对值不会超过1。

  下面的方法,若是平衡二叉树,则还会返回树的高度

结点结构:

struct node 
{
    int data;
    int height;
    node *lc;
    node *rc;
    node()
        : data(0)
        , height(0)
        , lc(0)
        , rc(0)
    {

    }
};

函数源码:

// 判断是否为平衡二叉树,若是,则返回树的高度
    // false - 不是平衡二叉树,true-是平衡二叉树
    bool is_avl_tree(node *pnode, int &deepth)
    {
        if ( NULL == pnode)
        {
            deepth = 0;
            return true;
        }

        int left_h = 0;
        int right_h = 0;

        if (is_avl_tree(pnode->lc, left_h) && is_avl_tree(pnode->rc, right_h))
        {
            int diff = abs(left_h - right_h);
            if (1 < diff)
                return false;
            deepth = 1 + ( (left_h > right_h) ? left_h : right_h);

            return true;
        }

        return false;
    }

猜你喜欢

转载自www.cnblogs.com/pandamohist/p/10581982.html