0

我正在尝试使用二叉搜索树数据结构,但我似乎无法完成将任何内容插入树中。每次我的程序调用插入函数时,它都认为树中没有任何内容。这是2个类:

template<typename T>
class TreeNode{
public:
    T m_data;
    TreeNode* m_right;
    TreeNode* m_left;
    TreeNode<T>(const T& data, TreeNode<T>* right, TreeNode<T>* left) : m_data(data), m_right(right), m_left(left){};
};

template<typename T>
class MyBSTree : public AbstractBSTree<T>{
protected:
    TreeNode<T>* m_root;
    int m_size;

这是功能:

    void rec_insert(TreeNode<T>* root, const T& x){
        if(root == NULL){
            cout << "Inserting here" << endl;
            TreeNode<T>* tmp = new TreeNode<T>(x, NULL, NULL);
            root = tmp;
        }
        else if(x < root -> m_data){
            cout << "Inserting left" << endl;
            rec_insert(root -> m_left, x);  
        }
        else if(x > root -> m_data){
            cout << "Inserting right" << endl;
            rec_insert(root -> m_right, x);
        }
        if(root == NULL)
            cout << "WHAT IS HAPPENING?" << endl;
        cout << "resizing" << endl;
        m_size++;
    };

插入几个项目的输出是这样的:

Inserting here
resizing
Inserting here
resizing

我真的不知道这里发生了什么,任何帮助将不胜感激。

4

1 回答 1

0

您需要对按引用传递和按值传递进行一些研究。

您将指针传递给您的插入方法 - 您只能在root本地更改值 - 您所做的任何更改都不会持续到函数调用之外。您需要通过引用传递以允许root更改并在rec_insert()方法之外查看更改。

另一种方法可能是重构您的代码以从rec_insert().

于 2013-11-14T03:46:59.590 回答