C++模板类的insert方法

insert method of C++ template class

本文关键字:insert 方法 C++      更新时间:2023-10-16

以下是我迄今为止实现的内容。执行后调试以下代码时"n=新节点(val,NULL,NULL);"在insert方法和离开insert方法中,一旦我离开该方法,"val"就不会保存在根节点中,我不明白为什么。

// Creates an empty binary tree
template<class T> binTree<T>::binTree() {
    root = NULL;
}
template<class T> void binTree<T>::insert(T val) {
    insert(val, root);
}
template<class T> void binTree<T>::insert(T val, node* n) {
    if (n == NULL) {
        n = new node(val, NULL, NULL); // <=============Not actually storing the value into the node after this method is done
    } else if (val < n->val) {
        if (n->left == NULL) {
            n->left = new node(val, NULL, NULL);
        } else {
            insert(val, n->left);
        }
    } else if (val > n->val) {
        if (n->right == NULL) {
            n->right = new node(val, NULL, NULL);
        } else {
            insert(val, n->right);
        }
    }
}

这是头文件中我的私有结构:

private:
    struct node {
        T val;
        node* left;
        node* right;
        node(T v, node* l, node* r) :
                val(v), left(l), right(r) {
        }
    };
    void destruct(node* n);
    void insert(T val, node* n);
    T find(T val, node* n) const;
    T remove(T val, node* n, node* parent);
    node* root;
};

您按值接受指针,因此您只修改局部变量n,当函数返回时,对其的更改将丢失。

也许你想参考n,就像node*& n一样?这意味着函数内部对n的更改将影响传递到函数中的参数。