我已经使用循环在BST中插入了一个函数,它工作得很好。 现在,当iam使用递归进行写操作时,我不知道为什么它不能正常工作,但根据我的逻辑是正确的。看起来没有newnode被添加到BST树和插入函数出来后树的头部再次变为NULL。BST的递归插入
#include <iostream>
using namespace std;
class node{
public:
int data;
node *right;
node *left;
node(){
data=0;
right=NULL;
left=NULL;
}
};
class tree{
node *head;
int maxheight;
void delete_tree(node *root);
public:
tree(){head=0;maxheight=-1;}
void pre_display(node* root);
node* get_head(){return head;}
void insert(int key,node* current);
};
void tree::insert(int key,node *current){
if(current==NULL)
{
node *newnode=new node;
newnode->data=key;
current=newnode;
}
else{
if(key<current->data)
insert(key,current->left);
else
insert(key,current->right);
}
return;
}
void tree::pre_display(node *root){
if(root!=NULL)
{
cout<<root->data<<" ";
pre_display(root->left);
pre_display(root->right);
}
}
int main(){
tree BST;
int arr[9]={17,9,23,5,11,21,27,20,22},i=0;
for(i=0;i<9;i++)
BST.insert(arr[i],BST.get_head());
BST.pre_display(BST.get_head());
cout<<endl;
system("pause");
return 0;
}
请告诉我在算法中应该改变什么才能使其工作。
但IAM发送头指针从主,因此电流将相同递归的一审头。 – Zohaib
您正在按值传递一个节点*。如果你通过引用BST ::头将被正确更新 –
但我想保持BST头私人。 – Zohaib