我试图用递归插入一个新的节点到BST中。
但插入后我失去了链接。
有序遍历表明程序只能访问根节点。
这是我的计划在二叉搜索树(C++)中插入的递归函数
类BST
class bst
{
struct node
{
struct node *lchild;
int info;
struct node *rchild;
}*start;
public:
bst();
void insert(int num,struct node *start);
void search(int num,struct node *start);
void display();
void inorder(node *start);
struct node *getRoot(){
return start;
}
};
插入功能
void bst :: insert(int num,struct node *ptr)
{
if(ptr == NULL)
{
ptr = new node;
ptr->info = num;
ptr->lchild = NULL;
ptr->rchild = NULL;
if(start == NULL)
start = ptr;
return;
}
else if(num < ptr->info)
{
insert(num,ptr->lchild);
}
else if(num > ptr->info)
{
insert(num,ptr->rchild);
}
else
{
cout << "Duplicate element \n";
return;
}
}
主要功能
int main()
{
bst S;
int option,key;
cout << "Enter an element\n";
cin >> key;
S.insert(key,S.getRoot());
}
如何维护正确的链接而不更改插入函数的返回类型?
您的节点结构真的可以使用一个构造函数。 – Borgleader 2014-10-06 15:17:30
@Borgleader对不起,我不明白。 – Pradeep 2014-10-06 15:18:27
@Rustam'getRoot()'函数在类中定义。 – Pradeep 2014-10-06 15:34:01