【问题标题】:Doubt Regarding Function to check whether a tree is balanced or not?怀疑检查树是否平衡的功能?
【发布时间】:2011-08-02 19:24:31
【问题描述】:
我在一本名为《Coding Interview Cracked》的书中读到,要检查 BST 是否平衡,只需找出最大和最小高度之间的差异,但我不确定它是否 100% 正确。虽然我找不到反测试用例。
任何人都可以确认这种方法是否正确。
用于检查树是否平衡。
|MaxHieght(root) - MinHieght(root)| <=1
return true
else return false
【问题讨论】:
标签:
algorithm
avl-tree
tree-balancing
【解决方案1】:
鉴于平衡的定义(来自 Pedias 的 Wiki)
节点的平衡因子是其左子树的高度减去
其右子树的高度(有时相反)和一个节点
平衡因子 1、0 或 -1 被认为是平衡的。任何一个节点
其他平衡因子被认为是不平衡的,需要重新平衡
那个树。平衡因子要么直接存储在每个节点,要么
根据子树的高度计算。
这似乎是正确的。由于 minHeight 和 maxHeight 将等于任一侧的高度,看起来定义成立
【解决方案2】:
如果你愿意,你也可以试试这个方法。
bool isBalanced(node curPtr)
{
static int heightLeft,heightRight; //Need to save previous return value
if ( !curPtr )
{
return 0;
}
heightLeft = isBalanced(curPtr->lChild);
heightRight = isBalanced(curPtr->rChild);
++heightLeft; // Height of the Tree should be atleast 1 ( ideally )
++heightRight;
return ( ( ( heightLeft - heightRight ) == 0 ) || (( heightRight - heightLeft ) == 0 ) );
}
HTH