二叉樹的遍歷

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

 
發佈了28 篇原創文章 · 獲贊 11 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章