这是我的代码。我想递归地将这些项插入到二叉树中。它不是一个二叉搜索树(left child不必parent)。
它只是一个二叉树,每个节点最多可以有两个子节点。当我执行遍历时,它只是以无限循环(5->5->5->5->…)无休止地打印出起始节点。请帮帮我。
我已经搜索过堆栈溢出,没有任何东西是基于此的。大多数是二进制搜索树。如果这个问题不好,我很抱歉。
struct node {
int info;
struct node* left;
struct node* right;
}*temp, *ptr, *prev;
struct node *root, *start=NULL;
void insert(struct node*);
void inorder(struct node*);
void insert(struct node* ptr)
{
int ch;
if(start==NULL) // if start is null, new node is made as start node.
start=ptr;
else
{
temp=(struct node*)malloc(sizeof(struct node)); //new node created
temp->left=NULL;
temp->right=NULL;
puts("Enter value");
scanf("%d", &temp->info);
ptr=temp; //ptr is set as new node
}
printf("Does %d have a left node? (1/0)\n", ptr->info);
scanf("%d", &ch);
if(ch==1)
{
prev=ptr;
if(ptr==start)
insert(start->left); //start->left will be the new 'ptr' in the next insertion scenario
else
insert(ptr->left); //same principle as above
}
printf("Does %d have a right node? (1/0)\n", ptr->info);
scanf("%d", &ch);
if(ch==1)
{
prev=ptr;
if(start==ptr)
insert(start->left);
else
insert(ptr->right);
}
}
void inorder(struct node* ptr)
{
while(ptr!=NULL)
{
inorder(ptr->left);
printf("%d -> ", ptr->info);
inorder(ptr->right);
}
}
void main(){
int ch;
do{
puts("1. Insert 2.Traverse 3.Exit");
scanf("%d",&ch);
switch(ch){
case 1:
puts("Enter root node");
root=(struct node *)malloc(sizeof(struct node));
root->left=NULL;
root->right=NULL;
scanf("%d", &root->info);
insert(root);
break;
case 2:
inorder(start);
}
}while(ch!=3);
}
提前谢谢,伙计们。
最佳答案
尝试以这种方式添加节点:
struct node *createTree()
{
struct node *node;
int resp;
node=malloc(sizeof(struct node)); //new node created
node->left=NULL;
node->right=NULL;
puts("Enter value");
scanf("%d", &node->info);
printf("Does %d have a left node? (1/0)\n", node->info);
scanf("%d", &resp);
if(resp==1)
node->left = createTree();
printf("Does %d have a right node? (1/0)\n", node->info);
scanf("%d", &resp);
if(resp==1)
node->right = createTree();
return node;
}
然后在
main()
中:root = createTree();
注意,如果使用
resp
格式扫描,则int
变量的类型为"%d"
。对于char
类型,应使用format"%c"
。