非递归遍历二叉树

C代码  收藏代码
  1. #include<stdio.h>  
  2. #include<malloc.h>  
  3.   
  4. typedef struct binode{  
  5.     char data;  
  6.     struct binode *lchild;  
  7.     struct binode *rchild;  
  8. }BiNode,*BiTree;  
  9. /**************************** 
  10.  *输入创建二叉树: abd##ef###c## 
  11.  *其实输入按照先序顺序,#表示叶子节点 
  12.  *****************************/  
  13. void create(BiTree t){  
  14.     char ch=(char)getchar();  
  15.     if(ch=='#'){  
  16.         t->data='#';  
  17.         t->lchild=NULL;  
  18.         t->rchild=NULL;  
  19.     }  
  20.     else{  
  21.         t->data=ch;  
  22.         t->lchild=(BiTree)malloc(sizeof(BiNode));  
  23.         create(t->lchild);  
  24.         t->rchild=(BiTree)malloc(sizeof(BiNode));  
  25.         create(t->rchild);  
  26.     }    
  27. }  
  28. //先序遍历  
  29. void preTraverse(BiTree t){  
  30.     BiTree p=t;  
  31.     BiTree stack[20]; //使用栈来替代递归方法  
  32.     int top=0;  
  33.     while(top>=0){  
  34.        while(p->data!='#'){  
  35.            printf("%c ",p->data);  
  36.            stack[top++]=p;  
  37.            p=p->lchild;  
  38.        }  
  39.        if(top>0)  
  40.           p=stack[--top]->rchild;  
  41.        else   
  42.           top=-1;  
  43.          
  44.     }  
  45. }  
  46. //中序遍历,和先序差不多  
  47. void midTraverse(BiTree t){  
  48.     BiTree p=t;  
  49.     BiTree stack[20];  
  50.     int top=0;  
  51.     while(top>=0){  
  52.         while(p->data!='#'){  
  53.            stack[top++]=p;  
  54.            p=p->lchild;  
  55.         }  
  56.         if(top>0){  
  57.            p=stack[--top];  
  58.            printf("%c ",p->data);  
  59.            p=p->rchild;  
  60.         }else  
  61.            top=-1;  
  62.     }  
  63. }  
  64. //后序遍历,稍微复杂一点  
  65. void afeTraverse(BiTree t){  
  66.     BiTree p=t,q=t;  
  67.     BiTree stack[20];  
  68.     int top=0;  
  69.     while(top>=0){  
  70.         while(p->data!='#'){  
  71.            stack[top++]=p;  
  72.            p=p->lchild;  
  73.         }  
  74.         if(q->rchild==p){  
  75.            printf("%c ",q->data);  
  76.            q->data='#'//遍历完的节点直接做叶子标记  
  77.            --top;   
  78.         }  
  79.         if(top>0){  
  80.            p=stack[top-1];  
  81.            q=p;  
  82.            p=p->rchild;  
  83.              
  84.         }  
  85.     }  
  86. }  
  87. //测试  
  88. int main(){  
  89.     BiTree root=(BiTree)malloc(sizeof(BiNode));  
  90.     create(root);  
  91.     afeTraverse(root);  
  92.     printf("\n");  
  93.     return 1;  
  94. }  
posted @ 2012-07-22 21:39  springbarley  阅读(149)  评论(0)    收藏  举报