二叉树的遍历

来源:互联网 发布:淘宝怎么创建子帐号 编辑:程序博客网 时间:2024/04/19 14:26
 

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

先序遍历:

中序遍历:

后序遍历:

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

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");
}
}