二叉树的中序、先序、后序遍历非递归遍历算法(使用堆栈,用循环实现)

 1 typedef struct TreeNode *BinTree;
 2 typedef    BinTree Position; 
 3 struct TreeNode{
 4     ElementType Data;
 5     BinTree Left;
 6     BinTree Right; 
 7 }; 
 8 BinTree BT;
 9 void InOrderTraversal(BinTree BT)//中序遍历非递归遍历算法(使用堆栈,用循环实现)
10 {
11     BinTree T=BT;
12     Stack S=CreakStack(MaxSize);//创建并初始化堆栈S
13     while(T||!IsEmpty(S)){
14         while(T){//一直向左并将沿途结点压入堆栈
15             Push(S,T);
16             T=T->Left; 
17         }
18         if(!IsEmpty(S)){
19             T=Pop(S);//结点弹出堆栈
20             printf("%5d",T->Data);//(访问)打印结点
21             T=T->Right;//转向右子树  
22         } 
23     } 
24 }
25 void PreOrderTraversal(BinTree BT)//先序遍历非递归遍历算法(使用堆栈,用循环实现)
26 {
27     BinTree T=BT;
28     Stack S=CreakStack(MaxSize);//创建并初始化堆栈S
29     while(T||!IsEmpty(S)){
30         while(T){//一直向左并将沿途结点压入堆栈
31             printf("%5d",T->Data);//(访问)打印结点
32             Push(S,T);
33             T=T->Left; 
34         }
35         if(!IsEmpty(S)){
36             T=Pop(S);//结点弹出堆栈
37             T=T->Right;//转向右子树  
38         } 
39     } 
40 }  
41 void PostOrderTraversal( BinTree BT )//后序遍历非递归遍历算法(使用堆栈,用循环实现)  
42 {  
43    BinTree T BT;  
44    Stack S = CreatStack( MaxSize ); /*创建并初始化堆栈S*/  
45    Stack Q = CreatStack( MaxSize ); /*创建并初始化堆栈Q,用于输出反向*/  
46    while( T || !IsEmpty(S) ){  
47        while(T){ /*一直向右并将沿途结点压入堆栈*/  
48            Push(S,T);  
49            Push(Q,T);/*将遍历到的结点压栈,用于反向*/  
50            T = T->Right;  
51        }  
52        if(!IsEmpty(S)){  
53        T = Pop(S); /*结点弹出堆栈*/  
54        T = T->Left; /*转向左子树*/  
55        }  
56    }  
57    while( !IsEmpty(Q) ){  
58        T = Pop(Q);  
59        printf(“%5d”, T->Data); /*(访问)打印结点*/  
60    }  
61 } 

 

posted on 2017-02-09 20:39  chy89224  阅读(323)  评论(0编辑  收藏  举报