先序遍历是一种遍历一个二叉树的方法,具体代码如下:
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
void xianxu(struct tree* root)
{
if(root!=NULL)
{
printf("%d ",root->data);
xianxu(root->left);
xianxu(root->right);
}
}
若用先序遍历来创立二叉树为:
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
struct tree* createnode(int data,struct tree* root)
{
root=(struct tree*)malloc(sizeof(struct tree));
if(data==0)
{
return NULL;
}
else {
root->left=NULL;
root->right=NULL;
root->data=data;
return root;
}
}
struct tree* bianli(struct tree* root)
{
int date;
scanf("%d",&date);
root=createnode(date,root);
if(root==NULL)
return;
root->left=bianli(root->left);
root->right=bianli(root->right);
}
完整代码是
#include<stdio.h>
#include<stdlib.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
struct tree* createnode(int data,struct tree* root)
{
root=(struct tree*)malloc(sizeof(struct tree));
if(data==0)
{
return NULL;
}
else {
root->left=NULL;
root->right=NULL;
root->data=data;
return root;
}
}
struct tree* bianli(struct tree* root)
{
int date;
scanf("%d",&date);
root=createnode(date,root);
if(root==NULL)
return;
root->left=bianli(root->left);
root->right=bianli(root->right);
}
void xianxu(struct tree* root)
{
if(root!=NULL)
{
printf("%d ",root->data);
xianxu(root->left);
xianxu(root->right);
}
}
int main()
{
struct tree* root=NULL;
printf("please enter the number\n");
root=bianli(root);
xianxu(root);
}