判断一棵二叉树是不是平衡二叉树

如果某二叉树中的任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

 

struct BinaryTreeNode 
{
    int value;
    BinaryTreeNode* p_left;
    BinaryTreeNode* p_right;
};


bool IsBalanced(BinaryTreeNode* pRoot, int* pDepth)
{
    if( pRoot == NULL)
    {
        *pDepth = 0;
        return true;
    }

    int left,right;
    if(IsBalanced(pRoot->p_left,&left) && IsBalanced(pRoot->p_right,&right))
    {
        int diff = left - right;
        if( diff <= 1 && diff >= -1)
        {
            *pDepth = 1 + (left > right ? left: right);
            return true;
        }
    }

    return false;
}

bool IsBalanced(BinaryTreeNode* pRoot)
{
    int depth=0;
    return IsBalanced(pRoot,&depth);
}

 

posted @ 2013-03-08 20:19  没离开过  阅读(125)  评论(0编辑  收藏  举报