#include <stdio.h>
#include <malloc.h>
typedef struct node
{
int data;
struct node *left;
struct node *right;
}node;
void print(node *p)
{
if(p!=NULL)
{
print(p->left);
printf("%d/n",p->data);
print(p->right);
}
}
void main()
{
int n;
scanf("%d",&n);
node *head=(node *)malloc(sizeof(node));
head->data =n;
head->left =NULL;
head->right =NULL;
scanf("%d",&n);
while(n!=-1)
{
node *p=(node *)malloc(sizeof(node));
p->data =n;
p->left=NULL;
p->right =NULL;
node *q=head;
node *f=q;
while(q!=NULL)
{
if(n<q->data )
{
f=q;
q=q->left ;
continue;
}
if(n>q->data )
{
f=q;
q=q->right ;
continue;
}
}
if(n<f->data ) f->left =p;
if(n>f->data ) f->right =p;
scanf("%d",&n);
}
print(head);
}
该博客给出一段C语言代码,定义了二叉树节点结构体,实现了节点插入和中序遍历功能。通过输入整数构建二叉树,输入 -1 结束,最后对构建好的二叉树进行中序遍历并输出节点数据。
461

被折叠的 条评论
为什么被折叠?



