二叉树的遍历

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

 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值