非常简单的前序遍历,建树使用递归算法
#include<stdio.h>
#include<stdlib.h>
struct node;
typedef struct node* A;
struct node
{
int data;
A left;
A right;
};
A insert(A node,int num);
void pre(A Tree);
void pre(A Tree)
{
if(Tree)
{
printf("%d,",Tree->data);
pre(Tree->left);
pre(Tree->right);
}
}
A insert(A node,int num)
{
if(node==NULL)
{
node=(A)malloc(sizeof(A));
node->data=num;
node->left=node->right=NULL;
}
else
{
if(num<node->data)
{
node->left=insert(node->left,num);
}
if(num>node->data)
{
node->right=insert(node->right,num);
}
}
return node;
}
int main()
{
int a=-1;
A B=NULL;
scanf("%d,",&a);
while(a!=-1)
{
B=insert(B,a);
a=-1;
scanf("%d,",&a);
}
pre(B);
return 0;
}