c++ - 来自 C++ 的 BST 代码

标签 c++

我想知道这个错误为什么被占用!!!

class node 
{
public:
    int data ;
    node *left ;
    node *right ;
} ;

class tree
{
public:
    node * root ;

public:
    tree() 
    {
        root = NULL ;
    }
    node* Insert(node* root, int num) // 
    {
        if(root == NULL) // root is null
        {
            node * temp = new node() ;
            temp->left = NULL ;
            temp->right = NULL ;
            temp->data = num ;
            root = temp ;
        }
        else if ( num < root->data )
        {
            root->left = Insert(root->left, num ) ;
        }
        else if ( num > root->data)
        {
            root->right = Insert(root->right, num ) ;
        }
        return root ;
    }
} ;
void main()
{
    tree * Tree = new tree() ;
    Tree->Insert(Tree->root, 10) ;
    cout << temp->root->data ;
}

当我执行这段代码时,我预计 root 的数据是 10。 但实际上,根是空的。 为什么 root 为空?

我不知道!!!!

请教我!!!

最佳答案

root 永远不会在您的 Insert 方法中更新。传递给方法的 root 与成员变量不同。

喜欢以下内容:

Tree->root = Tree->Insert(Tree->root, 10) ;

或传递根地址或在方法内的任何地方使用this->root =

总体而言,需要重新审视设计,我假设您想边玩边学

还要确保在完成后释放内存。目前到处都有内存泄漏。

关于c++ - 来自 C++ 的 BST 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37289406/

相关文章:

C++ 如何判断一个值是否赋给了一个变量?

c++ - 如何获得数字的按位非但不否定符号位?

c++ - 使用 å ä ö 按字母顺序排序

c++ - 关于 ODR 违规和模板变量

c++ - QList children - 从 QObject 派生的结构或自定义类?

c++ - 多态成员函数指针

c++ - 以 C++11 风格进行类型转换的正确方法?

c++ - 如何将字符串添加到我的结构数组中,该数组在 C++ 中同时包含字符串和整数?

c++ - 为什么 std::multimap 没有 [] 运算符?

c++ - 关于C++内部类的问题