简体   繁体   English

Function 检查二叉树是否平衡 C++

[英]Function to check in a binary tree is balanced C++

I'm trying to implement a function that uses recursion to check if a binary search tree is balanced.我正在尝试实现一个 function ,它使用递归来检查二叉搜索树是否平衡。

The template for the function I am using is我使用的 function 的模板是

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

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

}
}

Ive also created a function that checks the number of leaf nodes in the tree我还创建了一个 function 来检查树中叶节点的数量

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

From what I've read and saw, there needs to be something that gets the height of the left and right nodes.根据我的阅读和看到,需要有一些东西可以获取左右节点的高度。 Is the second function able to be used for that purpose or am I overlooking something.第二个 function 是否可以用于该目的,或者我是否忽略了某些东西。

Any help to get this solved would be appreciated as all my attempts have not worked.由于我的所有尝试都没有奏效,因此将不胜感激任何帮助解决此问题。

if needed this is the BSTNODE class如果需要,这是 BSTNODE class

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

Ended up working it out.最终解决了。 I had confused myself by thinking I needed another function for the height.我以为我需要另一个 function 作为高度,我感到很困惑。 Below is the code i used下面是我使用的代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM