您的位置:首页 > 其它

判断一棵树是否为平衡二叉树

2015-05-27 21:57 337 查看
typedef char DataType;

typedef struct TNode
{
DataType value;
struct TNode* leftchild;
struct TNode* rightchild;
}TreeNode;

//求解树的高度
int TreeDepth(TreeNode* tree)
{
if(tree==NULL)
{
return 0;
}
int leftDepth = tree->leftchild;
int righDepth = tree->rightchild;
return (leftDepth>rightchild)?(leftDepth+1):(rightchild+1);
}

//判断一棵树是否为平衡二叉树
bool IsBalanced(TreeNode* tree)
{
if(tree==NULL)
{
return true;
}

int leftDepth = TreeDepth(tree->leftchild);
int rightDepth = TreeDepth(tree->rightchild);
int diff = leftDepth - rightDepth;

if(diff>1 || diff < -1)
{
return false;
}

return (IsBalanced(tree->leftchild)
&& IsBalanced(tree->rightchild));

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: