标签:
C语言非递归实现二叉树的先序、中序、后序、层序遍历代码如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <stack> 4 #include <queue> 5 using namespace std; 6 7 //*****二叉树的二叉链表存储表示*****// 8 typedef struct BiNode 9 { 10 char data; 11 struct BiNode *lchild, *rchild; 12 int visitCount; 13 }BiNode, *BiTree; 14 15 //*****按先序次序输入二叉树中结点的值(一个字符),空格字符表示空树构造二叉链表表示的二叉树T*****// 16 void CreateBiTree(BiTree &T) 17 { 18 char ch; 19 scanf("%c", &ch); 20 if(ch == ‘ ‘) 21 { 22 T = NULL; 23 } 24 else 25 { 26 if(!(T = (BiNode *)malloc(sizeof(BiNode)))) 27 { 28 return; 29 } 30 T->data = ch; //生成根结点 31 T->lchild = NULL; 32 T->rchild = NULL; 33 CreateBiTree(T->lchild); //构造左子树 34 CreateBiTree(T->rchild); //构造右子树 35 } 36 37 return; 38 } 39 40 //*****先序遍历二叉树*****// 41 void PreOrderTraverse(BiTree T) 42 { 43 stack<BiTree> TreeStack; 44 BiTree p = T; 45 46 while (p || !TreeStack.empty()) 47 { 48 if (p) 49 { 50 printf("%c ", p->data); 51 TreeStack.push(p); 52 p = p->lchild; 53 } 54 else 55 { 56 p = TreeStack.top(); 57 TreeStack.pop(); 58 p = p->rchild; 59 } 60 } 61 } 62 63 //*****中序遍历二叉树*****// 64 void InOrderTraverse(BiTree T) 65 { 66 stack<BiTree> TreeStack; 67 BiTree p = T; 68 69 while (p || !TreeStack.empty()) 70 { 71 if (p) 72 { 73 TreeStack.push(p); 74 p = p->lchild; 75 } 76 else 77 { 78 p = TreeStack.top(); 79 printf("%c ", p->data); 80 TreeStack.pop(); 81 p = p->rchild; 82 } 83 } 84 } 85 86 //*****后序遍历二叉树*****// 87 void PostOrderTraverse(BiTree T) 88 { 89 stack<BiTree> TreeStack; 90 BiTree p = T; 91 92 while (p || !TreeStack.empty()) 93 { 94 if (p) 95 { 96 p->visitCount = 1; 97 TreeStack.push(p); 98 p = p->lchild; 99 } 100 else 101 { 102 p = TreeStack.top(); 103 TreeStack.pop(); 104 if (p->visitCount == 2) 105 { 106 printf("%c ", p->data); 107 p = NULL; 108 } 109 else 110 { 111 p->visitCount++; 112 TreeStack.push(p); 113 p = p->rchild; 114 } 115 } 116 } 117 } 118 119 //*****层序遍历二叉树*****// 120 void LevelOrderTraverse(BiTree T) 121 { 122 if (!T) 123 { 124 return; 125 } 126 127 queue<BiTree> TreeQueue; 128 TreeQueue.push(T); 129 BiTree p = T; 130 while (!TreeQueue.empty()) 131 { 132 p = TreeQueue.front(); 133 TreeQueue.pop(); 134 printf("%c ", p->data); 135 136 if (p->lchild) 137 { 138 TreeQueue.push(p->lchild); 139 } 140 if (p->rchild) 141 { 142 TreeQueue.push(p->rchild); 143 } 144 } 145 } 146 147 int main(void) 148 { 149 BiTree T; 150 printf("请按先序次序输入二叉树中结点的值(字符),空格字符表示空树:\n"); 151 CreateBiTree(T); 152 153 printf("先序遍历结果为:"); 154 PreOrderTraverse(T); 155 printf("\n\n"); 156 157 printf("中序遍历结果为:"); 158 InOrderTraverse(T); 159 printf("\n\n"); 160 161 printf("后序遍历结果为:"); 162 PostOrderTraverse(T); 163 printf("\n\n"); 164 165 printf("层序遍历结果为:"); 166 LevelOrderTraverse(T); 167 printf("\n\n"); 168 169 return 0; 170 }
以如下二叉树为例,给出按先序次序输入二叉树中结点的值(字符),从而按照本文给出的算法构造二叉树。
输入字符的顺序是:-+a空格空格*b空格空格-c空格空格d空格空格/e空格空格f空格空格,即可验证本文提供的遍历算法。
标签:
原文地址:http://www.cnblogs.com/mengwang024/p/4232169.html