二叉树的遍历

 

二叉树有:先序遍历后序遍历中序遍历

先序遍历:

中序遍历:

后序遍历:

先要做得是建立链表,链表用递归的方法:

void creat(BiTree *root,int i)

 {

        if(i>=l||s[i]=='.')

                 *root=NULL;//如果输入点就表示空;

      else

         {

               *root=(BiTree)malloc(sizeof(BiNode));//开辟新空间;

                       (*root)->data=s[i];

               creat(&((*root)->LChild),2*i+1); //递归。

               creat(&((*root)->RChild),2*i+2);

    }

 }

遍历:(以后序为例)

void PreOrder(BiTree root)

 {

        if(root!=NULL)

       {

            PreOrder(root->LChild);//输出结点;

              PreOrder(root->RChild);

             printf("%c",root->data);

 }

}

主函数:

void main()

 {

           BiTree T; //跟结点‘

            while(scanf("%s",s)!=EOF)

            {

                  l=strlen(s);//计算长度;

                  i=0;

                   creat(&T,i);

                  PreOrder(T);

                  printf("\n");

            }

 }

完整的函数:

#include<stdio.h>
  #include<stdlib.h>
  #include <string.h>
typedef struct Node
{ char data;
struct Node *LChild;
struct Node *RChild;
 }BiNode,*BiTree;
  char s[100];
   int l,i;
void creat(BiTree *root, int i)
{
if(i>=l||s[i]=='.') *root=NULL;
  else
 {
 *root= (BiTree) malloc( sizeof(BiNode));
  (*root)->data=s[i];
  creat(& ( (*root)->LChild),2*i+1);
  creat(& ( (*root)->RChild),2*i+2);
 }
 }
void PreOrder(BiTree root)
 {
if(root!=NULL)
{
PreOrder(root->LChild);
  PreOrder(root->RChild);
printf( "%c",root->data);
}
 }
void main()
{ BiTree T;
  while( scanf( "%s",s)!=EOF)
 {
 l= strlen(s);
 i=0;
  creat(&T,i);
PreOrder(T);
printf( "\n");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值