【发布时间】:2013-11-14 11:46:59
【问题描述】:
我正在尝试处理二叉搜索树数据结构,但我似乎无法完成将任何内容插入到树中。每次我的程序调用插入函数时,它都认为树中没有任何内容。以下是 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
我真的不知道这里发生了什么,任何帮助将不胜感激。
【问题讨论】:
-
您在函数中更改了 root 的值,但它不会反映在您的调用函数中。那是你的问题。
标签: c++ recursion binary-search-tree