C语言实现二叉树的前序遍历(递归)
C语言实现二叉树的前序遍历
算法实现一: #include
#include
typedef struct BiTNode//定义结构体
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T) //前序创建树
{
char ch;
scanf("%c",&ch);
if(ch==' ') T=NULL;
else
{
T=(struct BiTNode *)malloc(sizeof(struct BiTNode)); T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
int print(BiTree T)//前序遍历(输出二叉树)
{
if(T==NULL)return 0;
else if(T->lchild==NULL && T->rchild==NULL)return 1; else return print(T->lchild)+print(T->rchild); }
void main()//主函数
{
BiTree T;
CreateBiTree(T);
printf("%d\n",print(T));
}
算法实现二:
#include