【问题标题】:Function to check in a binary tree is balanced C++检查二叉树的函数是平衡的 C++
【发布时间】:2020-09-08 03:52:00
【问题描述】:

我正在尝试实现一个使用递归来检查二叉搜索树是否平衡的函数。

我正在使用的函数的模板是

template<class T>
int BST<T>::is_balanced(BSTNode<T> *p) const
{

    if (p == 0) // Base case
        return 0;
    else {

}
}

我还创建了一个检查树中叶节点数量的函数

template<class T>
int BST<T>::number_of_leaves(BSTNode<T>* start) const 
{
    if(start == NULL)
    {
        return 0;
    }
    if(start->right == NULL && start->left==NULL)
    {
        return 1;
    }
    return number_of_leaves(start->right) + number_of_leaves(start-> left);
}

根据我的阅读和所见,需要有一些东西可以获取左右节点的高度。第二个功能是否可以用于该目的,还是我忽略了某些东西。

由于我的所有尝试都没有奏效,因此我们将不胜感激。

如果需要,这是 BSTNODE 类

template<class T>
class BSTNode {
public:
    BSTNode() { left = right = 0; }
    BSTNode(const T& e, BSTNode<T> *l = 0, BSTNode<T> *r = 0) 
        { el = e, left = l, right = r; }
    T el;
    BSTNode<T> *left, *right;
};

【问题讨论】:

  • 您的代码似乎正在尝试解决不同的问题。叶子的数量在这里有什么关系?尝试获取树的高度,并检查每个节点的子树高度之间的绝对差是否小于 1。
  • 我尝试过使用 geeksforgeeks 方法,但对于我的测试,它只是说所有树都是平衡的,我将在初始帖子中添加示例

标签: c++ recursion tree binary-search-tree


【解决方案1】:

最终解决了。我以为我需要另一个高度函数而使自己感到困惑。下面是我使用的代码

template<class T>
int BST<T>::is_balanced(BSTNode<T>* root) const
{
        if(root == NULL)
        return 0;
        else {
                int lh = is_balanced(root->left);
                int rh= is_balanced(root->right);
                if (lh == -1 || rh == -1) return -1;
        if (abs(lh-rh) > 1) return -1;
        if(lh > rh) return lh +1;
        return rh+1;
        }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    相关资源
    最近更新 更多