问答题 如何判断二叉树是否是平衡二叉树
【正确答案】
【答案解析】根据平衡二叉树的定义可知,每个结点的左右子树的高度差小于等于1,只需在计算二叉树高度时,同时判断左右子树的高度差即可。
所以可以采用递归的方式来判断,算法如下:
int TreeHteight(const Node*root,bool&balanced)
{
const int LHeight=root->left?TfeetHeight(root->left,balanced)+1:0;
if (!balanced)
return 0;
const int RHeight=root->right?TreeHeight(root->right,balanced)+1:0;
if(!balanced)
return 0;
const int diff=LHeight-RHeight;
if(diff<-1‖diff>1)
balanced=false;
return (LHeight>RHeight?LHeight:RHeight);
}
bool IsBalancedTree(const Node*root)
{
bool balanced=true;
if(root)
TreeHeight(root,balanced);
return balanced;
}