二叉树的遍历

来源:互联网 发布:乐乎lofter下载 编辑:程序博客网 时间:2024/04/25 17:26

(1)、二叉树的链表形式的建立;

(2)、用递归方式写出二叉树的先序、中序、后序三种遍历方法。

       (3)、用非递归方式写出二叉树的中序遍历程序。

#include<stdio.h>
#define MAXSIZE 100
typedef struct BiTNode
{
    char data;
    struct BiTNode *lchild, *rchild;
}BiTNode,*BiTree;

BiTree CreateBiTree()
{
  BiTree T;
  char ch=getchar();
  if(ch=='#')
  T=NULL;
   else
  {
     T=(BiTNode *)malloc(sizeof(BiTNode));
     T->data=ch;
     T->lchild=CreateBiTree();
     T->rchild=CreateBiTree();
  }
  return T;
}              //递归生成二叉树,用#代表空子树

void preorder(BiTree t)
{
    if(t)
    {
       printf("%c ",t->data);
       preorder(t->lchild);
       preorder(t->rchild);
    }
}                   //递归先序遍历


void Inorder(BiTree T)
{
     if(T)
     {
         Inorder(T->lchild);
         printf("%c ",T->data);
         Inorder(T->rchild);
     }
}

                             //递归中序遍历

 

void postorder(BiTree t)
{
    if(t)
    {
       preorder(t->lchild);
       preorder(t->rchild);
       printf("%c ",t->data);
    }
}                                //递归后序遍历

 

 

void NInorder(BiTree T)
{
    BiTree stack[MAXSIZE];
    BiTree p=T;
    int top=-1;
    while(p||top!=-1)
    {
        if(p)
        {
            top++;
     stack[top]=p;
            p=p->lchild;
        }
        else
        {
     p=stack[top];
            top--;
            printf("%c ",p->data);
            p=p->rchild;
        }
    }
}                             //非递归中序遍历

main()
{
  BiTree T;
  printf("please input the tree: ");
  T=CreateBiTree();
  printf("/n");
  getch();

  printf("the tree after preorder is: ");
  preorder(T);
  printf("/n");
  getch();

  printf("the tree after ineorder is: ");
  Inorder(T);
  printf("/n");
  getch();

  printf("the tree after postorder is: ");
  postorder(T) ;
  printf("/n");
  getch();

  printf("the tree after noinorder is: ");
  NInorder(T) ;
  printf("/n");
  getch();
}