【问题】提供一颗二叉树,判断是否为平和二叉树
【代码】GetDepth()用来获取一个节点的深度,当一个节点的左右孩子的深度之差不超过1,就认为这是个平衡二叉树
int GetDepth(BTreeNode* root) {
if(root == NULL)
return 0;
int leftDepth = GetDepth(root->leftchild);
int rightDepth = GetDepth(root->rightchild);
return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
}
bool IsBalanceTree(BTreeNode *root) {
if (root == NULL)
return true;
int distance = abs(GetDepth(root->leftchild) - GetDepth(root->rightchild));
if (distance > 1)
return false;
else
return IsBalanceTree(root->leftchild) && IsBalanceTree(root->rightchild);
}
本文介绍了一种检测二叉树是否平衡的方法。通过递归计算每个节点的左右子树深度,若任意节点左右子树深度差超过1,则该二叉树不平衡。平衡二叉树有助于确保树操作的时间效率。

3174

被折叠的 条评论
为什么被折叠?



