ここで私はバイナリ検索ツリーを実装しようとしています。グローバルコンテキストでルートノードを宣言しました。私はリンクリストを実装したのと同じアイデアをたどりました。しかし、 .Iは、誰も私がpush()
で私のBSTに要素が挿入されない理由
#include<stdio.h>
struct node {
int data;
struct node *left;
struct node *right;
};
void insert(int value);
void push(struct node *temp,struct node *newNode);
struct node *root;
int main(){
root= NULL;
int option,value;
for(;;){
printf("Please select an option from below : \n");
printf("1 for insert\n");
printf("2 for search\n");
printf("please enter your option : ");
scanf("%d",&option);
printf("\n");
switch(option){
case 1:
printf("you choose to insert\n");
printf("input your value :");
scanf("%d",&value);
insert(value);
printf("\n");
break;
case 2:
printf("You choose to search\n");
printf("enter your value : ");
scanf("%d",&value);
search(root,value);
printf("\n");
default:
break;
}
}
}
void insert(int value){
struct node *newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
push(root,newNode);
}
void push(struct node *root_node,struct node *newNode){
if(root_node==NULL){
root_node = newNode;
printf("inserted\n\n\n");
}else{
if(root_node->data > newNode->data){
push(root_node->left,newNode);
printf("left\n");
}else{
push(root_node->right,newNode);
printf("right\n");
}
}
}
'push()'では、 'root_node = newNode;'は呼び出しコードに影響を与えないので、目的を果たしません。この上に多くの愚か者。おそらく[この1つ](http://stackoverflow.com/questions/20172603/why-do-we-need-to-return-the-head-pointer-in-a-bst-after-inserting-node)? – chux
あなたは少し説明してくださいできます..私はまだ混乱しています! –
C *で参照渡しを*エミュレートすることについて検索して読んでください。 –