ループを使用してBSTに挿入する機能を作成しました。完全に正常に動作しています。 今、iamが再帰を使用してそれを行うときに、なぜそれが正しく動作しているのかわからないのですが、論理は正しいと思います。新しいノードが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 :: headは正しく更新されます –
しかし、私はBSTヘッドを非公開にしておきたいと思います。 – Zohaib