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

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

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

       平衡二叉树必须满足两个条件: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);
}

 

转载于:https://www.cnblogs.com/menghuizuotian/p/3828534.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值