关于检查树是否平衡的函数的疑问?

发布于 2024-11-27 17:01:03 字数 248 浏览 2 评论 0原文

我在《Coding Interview Cracked》一书中看到,要检查 BST 是否平衡,只需找出最大和最小高度之间的差异,但我不确定它是否 100% 正确。虽然我无法找到反测试用例。

任何人都可以确认这种方法是否正确。

用于检查树是否平衡。

|MaxHieght(root) - MinHieght(root)| <=1
   return true
else return false

I read in a book named "Coding Interview Cracked", that to check whether a BST is balanced or not, just find out the difference between the maximum and minimum height but I not sure whether it is 100% correct. Though I am unable to find a counter test case.

Can anyone confirm whether this approach is correct or not.

For checking whether a tree is balanced or not.

|MaxHieght(root) - MinHieght(root)| <=1
   return true
else return false

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若言繁花未落 2024-12-04 17:01:03

给出平衡的定义(来自 Pedias Wiki)

节点的平衡因子是其左子树的高度减去
其右子树(有时是相反的)和节点的高度
平衡因子 1、0 或 -1 被认为是平衡的。一个节点具有任意
其他平衡因素被认为不平衡,需要重新平衡
树。平衡因子要么直接存储在每个节点上,要么
根据子树的高度计算。

这似乎是正确的。由于 minHeight 和 maxHeight 将等于任一侧的高度,因此看起来定义成立

Given the definition of balanced (from the Wiki of Pedias)

The balance factor of a node is the height of its left subtree minus
the height of its right subtree (sometimes opposite) and a node with
balance factor 1, 0, or −1 is considered balanced. A node with any
other balance factor is considered unbalanced and requires rebalancing
the tree. The balance factor is either stored directly at each node or
computed from the heights of the subtrees.

This seems correct. Since the minHeight and maxHeight are going to be equal to the height of either side, looks like the definition holds

海夕 2024-12-04 17:01:03

如果您愿意,也可以尝试这种方式。

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 ) );
}

华泰

You can try this way also, if you feel like.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文