平衡二叉树即左右子树差的绝对值不超过1,任意给定一棵树,判断它是否是平衡二叉树
具体思路:可以将问题分成两步进行:第一步先实现求解二叉树中每个结点高度的函数height,;第二步先序遍历二叉树中的每
一个结点,调用height求出每一个结点左右子树的高度,根据左右子树的高度判断是否是平衡二叉树
typedef struct BTNode
{
int data;
struct BTNode *child,*rchild;
}BTNode,*root;
int height(BTNode *root)
{
if(root==NULL)
return 0;
int left_height=height.(root.lchild);
int right_height=height(root.rchild);
return (left_height>right_height ? left_height : right_height) +1;
}
bool isBalance(BTNode *root)
{
if(root==NULL)
return true;
int left_height=height(root->lchild); ///这三行相当于先访问结点
int right_height=height(root->rchild); ///
if(abs(left_height-right_height) >1) ///
return false;
else
return isBalance(root->lchild) && isBalance(root->rchild); //相当于再访问该结点的左子树,然后再访问该结点的右子树
}
算法分析:采用先序遍历,每一个结点在求其子树高度的过程中都存在重复操作,故时间复杂度比较大。根本原因在于采用了先序遍历的思想,而求根的高度,又必须知道其左右子树的高度。
算法优化:采用后序遍历的思想,先已经知道了某结点左右子树的情况,如果左右子树中有一个不满足平衡二叉树,那么都不需要再去求解结点的高度了。
bool isBalance(BTNode *root,int & height)
{
if(root==NULL)
{
height=0;
return true;
}
int left_height;
int right_height;
if(isBalance(root-<lchild,left_height) && isbalance(root->rchild,right_height)) //此处相当于先访问左右孩子
{
int balindex=left_height - right_height;
if(balindex<=1)
{
height=(left_height >right_height ? left_height: right_height)+1; //访问根节点
return true;
}
}
return false;
}