输入一颗二叉树的根节点,判断该树是不是平衡二叉树

来源:互联网 发布:球球大作战辅助软件 编辑:程序博客网 时间:2024/04/30 12:48
输入一颗二叉树的根节点,判断该树是不是平衡二叉树

1. 解法一
    该解法的思路:在遍历树的每个节点的时候,调用函数TreeDepth得到它的左右子树的深度。如果每个节点的左右子树的深度相差都不超过1,按照定义就是一棵平衡的二叉树。
代码为:

bool IsBalanced(BinaryTreeNode* pRoot)
{
    if(pRoot==NULL)
         return false;
    int left=TreeDepth(pRoot->m_pLeft);
    int right=TreeDepth(pRoot->m_pRight);
    int diff=left-right;
    if(diff>1||diff<-1)
       return false;
    return IsBalanced(pRoot->m_pLeft)&& IsBalanced(pRoot->m_pRight);;
}

int TreeDepth(BinaryTreeNode* pRoot)
{
   if(pRoot==NULL)
       return 0;
   int nLeft=TreeDepth(pRoot->m_pLeft);
   int nRight=TreeDepth(pRoot->m_pRight);
   return (nLeft>nRight)?(nLeft+1):(nRight+1);
}
上面的方法有着重复遍历节点多次的缺点。

2. 解法二
    如果我们用后序遍历的方式遍历二叉树的每一个节点,在遍历到一个节点之前我们就已经遍历了它的左右子树。只要在遍历每个节点的时候记录了它的深度,我们就可以一边遍历一边判断每个节点是不是平衡的。
代码为:
bool IsBalanced(BinaryTreeNode* pRoot,int *depth)
{
    if(pRoot==NULL)
    {
        *depth=0;
        return true;
    }
    int left;
    int right;
    if(IsBalanced(pRoot->m_pLeft,&left) && IsBalanced(pRoot->m_pRight,&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);
}