这里我试图实现一个二叉搜索树。我在全局上下文中声明了根节点。我遵循同样的想法,我如何实现链表。但是这种方法看起来并不像工作。我找不出什么是错在这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 *中的引用传递。 –