gpt4 book ai didi

c - 为什么 create 函数返回的地址与第一个节点的根地址不同

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:01 25 4
gpt4 key购买 nike

下面是我的 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??)

最佳答案

打印调用 create 的结果,然后为返回值再次调用 create ,从而创建第二个节点。

关于c - 为什么 create 函数返回的地址与第一个节点的根地址不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31973366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com