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

题目: 输入一棵二叉树的根节点,判断该树是不是平衡二叉树。

分析:首先要明白平衡二叉树的概念:

       平衡二叉树必须满足两个条件:1)左右子树的高度差不能大于1   2)每个根节点下面的左右子树也必须满足平衡二叉树的性质。

       对于本题,我们首先要知道如何去求一棵二叉树的深度,接下来我们只需要判断每个节点是否满足平衡二叉树的性质不就完了。所以就有了第一种方法的出现。

       但是第一种方法有一个问题就是,有些节点会被重复遍历,为了克服这个问题,我们可以一边遍历一边判断每个节点是否平衡。

 

struct BinaryTreeNode{
    int m_value;
    BinaryTreeNode * p_leftTreeNode;
    BinaryTreeNode * p_rightTreeNode;
};

int GetTreeDepth(BinaryTreeNode* pNode)
{
    if (pNode == NULL)
        return 0;
    int nLeft, nRight;
    if (pNode->p_leftTreeNode != NULL)
        nLeft = GetTreeDepth(pNode->p_leftTreeNode) + 1;
    if (pNode->p_rightTreeNode != NULL)
        nRight = GetTreeDepth(pNode->p_rightTreeNode) + 1;
    return (nLeft > nRight) ? nLeft : nRight;
}
//1.时间复杂度为 O((logn)!) ,其中有些节点被重复遍历了,效率不高
bool isBalanced(BinaryTreeNode *pNode)
{
    if (pNode == NULL)
        return true;
    //判断为平衡二叉树必须满足两个条件
    //条件1,一个节点的左右子树之间的高度差必须小于等于1
    int nLeftDepth = GetTreeDepth(pNode->p_leftTreeNode);
    int nRightDepth = GetTreeDepth(pNode->p_rightTreeNode);
    int nDiffInDepth = nLeftDepth - nRightDepth;
    if (nDiffInDepth<-1 || nDiffInDepth>1)
        return false;
    //条件2.一个节点下面的左右子树分别也要满足平衡二叉树的要求
    return (isBalanced(pNode->p_leftTreeNode) && (isBalanced(pNode->p_rightTreeNode)));
}
//2.更好的方法,这里很好的解决了第一种方法的问题,就是遍历每个节点的时候,我们用pDepth记录其深度,
    //那么我们就可以一边遍历一边判断每个节点是不是平衡的
bool isBalanced(BinaryTreeNode* pNode,int *pDepth)
{
    if (pNode == NULL)
    {
         return true;
         *pDepth = 0;
    }
    int nLeft, nRight;
    int nDiffInDepth;
    if (isBalanced(pNode->p_leftTreeNode, &nLeft) && isBalanced(pNode->p_rightTreeNode, &nRight))
    {
        nDiffInDepth = nLeft - nRight;
        if (nDiffInDepth >= -1 && nDiffInDepth <= 1)
        {
            *pDepth = nLeft > nRight ? nLeft : nRight + 1;
            return true;
        }
    }
    return false;    
}
bool isBalanced(BinaryTreeNode* pNode)
{
    int nDepth = 0;  //深度最开始初始化为0
    return isBalanced(pNode, &nDepth);
}

 

posted @ 2014-07-06 21:15  menghuizuotian  阅读(3755)  评论(0编辑  收藏  举报