這裏我試圖實現一個二叉搜索樹。我在全局上下文中聲明瞭根節點。我遵循同樣的想法,我如何實現鏈表。但是這種方法看起來並不像工作。我找不出什麼是錯在這code.Can誰能幫我算出這個爲什麼沒有元素被插入到我的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;'沒有任何用處,因爲它不影響調用代碼。這一個很多愚蠢。也許[這一個](http://stackoverflow.com/questions/20172603/why-do-we-need-to-return-the-head-pointer-in-a-bst-after-inserting-node)? – chux
可以請你解釋一下..我還是很困惑! –
搜索並閱讀*模擬C *中的引用傳遞。 –