以下是我的BST代码: 插入工作正常,但搜索不是
typedef struct tree_node{
struct tree_node* parent;
struct tree_node* left;
struct tree_node* right;
int x;
}tree_node;
tree_node *strt=NULL;
tree_node *traverse;
tree_node* create(int info){
tree_node *temp=NULL;
temp=(tree_node*)malloc(sizeof(tree_node));
temp->parent=NULL;
temp->left=NULL;
temp->right=NULL;
temp->x=info;
return temp;
}
tree_node* insert(tree_node *root, int a){
/* here i am printing the address of the node which must be same as the root for the first node */
if(root==NULL){
printf("%d ",create(a));
return create(a);
}
else if(a <= root->x)
return insert(root->left,a);
else
return insert(root->right,a);
return root;
}
tree_node* search_ele(tree_node *root,int info){
if(root==NULL || root->x==info)
return root ;
if(info < root->x)
return search_ele(root->left,info);
else
return search_ele(root->right,info);
}
void display_inorder(tree_node *root){
if(root==NULL)
return;
display_inorder(root->left);
printf("%d ",root->x);
display_inorder(root->right);
}
void main(){
int element;
tree_node *search_element;
while(1){
char ch;
int num;
printf("\nWant to enter a node..??\n\n");
scanf(" %c",&ch);
if(ch=='n'||ch=='N')
break;
else{
printf("Enter the number \n");
scanf("%d",&num);
if(strt==NULL)
printf("Tree is empty...entering first node...!!!\n");
strt=insert(strt,num);
printf("%d",strt);
}
}
printf("Enter the element u want to search\n");
scanf("%d ",&element);
if(search_ele(strt,element)==NULL)
printf("no such element\n");
else
printf("element found\n");
display_inorder(strt);
}
输出显示:
Want to enter a node ?
y
Enter the number
6
Tree is empty...entering first node...!!!
5279480 5279504 (why are these different??)
答案 0 :(得分:2)
您打印调用Job-Test $foo $bar
的结果,然后再次调用create
作为返回值,从而创建第二个节点。
答案 1 :(得分:1)
首先是BST算法的问题:您的节点创建算法从不将新节点附加到父节点。 Create()将node-&gt; parent设置为NULL,而insert()永远不会将父变量更新为root。此外,您永远不会设置新节点的父级的新左/右字段
更改
return create(a)
到
tree_node * new_node = create(a);
new_node->parent=root;
new_node->parent->left/right=new_node; //include some way to distinguish whether you went left or right in the previous recursive call
return new_node
现在,对于你的地址问题,你调用create()两次,其中(从程序上来说)会导致两个malloc()调用,从而产生两个地址。