1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
| #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<string> #include<stack> #include<queue> #include<algorithm> #include<iostream> #define TElemType int using namespace std;
typedef struct BiTNode { TElemType data; struct BiTNode *lchild, *rchild; }BiTNode, *BiTree;
int InitTree(BiTree &T) { TElemType a; scanf("%d", &a); if (-1 == a) T = NULL; else { T = (BiTree)malloc(sizeof(BiTNode)); T->data = a; InitTree(T->lchild); InitTree(T->rchild); } return 0; }
void PreOrder(BiTree T) { if (T != NULL) { printf("%d ", T->data); PreOrder(T->lchild); PreOrder(T->rchild); } }
void InOrder(BiTree T) { if (T != NULL) { InOrder(T->lchild); printf("%d ", T->data); InOrder(T->rchild); } }
void PostOrder(BiTree T) { if (T != NULL) { PostOrder(T->lchild); PostOrder(T->rchild); printf("%d ", T->data); } }
void LevelOrder(BiTree T) { queue<BiTNode> q; if (T != NULL) { BiTNode temp; q.push(*T); while (!q.empty()) { temp = q.front(); q.pop(); printf("%d ", temp.data); if (temp.lchild != NULL) q.push(*temp.lchild); if (temp.rchild != NULL) q.push(*temp.rchild); } } }
void CreateBiTree(BiTree &T) { printf("请按照先序遍历输入二叉树(-1无):"); InitTree(T); printf("二叉树先序遍历序列:"); PreOrder(T); printf("\n"); }
void Traverse(BiTree T) { int choice; while (1) { printf("********1.先序遍历 2.中序遍历*********\n"); printf("********3.后序遍历 4.层次遍历*********\n"); printf("********5.返回上一单元\n"); printf("请输入菜单序号:\n"); scanf("%d", &choice); if (5 == choice) break; switch (choice) { case 1: {printf("二叉树先序遍历序列:");PreOrder(T);printf("\n");}break; case 2: {printf("二叉树中序遍历序列:");InOrder(T);printf("\n");}break; case 3: {printf("二叉树后序遍历序列:");PostOrder(T);printf("\n");}break; case 4: {printf("二叉树层次遍历序列:");LevelOrder(T);printf("\n");}break; default:printf("输入错误!!!\n");break; } } }
void menu() { printf("********1.创建 2.遍历*********\n"); printf("********3.退出\n"); }
int main() { BiTree T = NULL;int choice = 0; while (1) { menu(); printf("请输入菜单序号:\n"); scanf("%d", &choice); if (3 == choice) break; switch (choice) { case 1:CreateBiTree(T);break; case 2:Traverse(T);break; default:printf("输入错误!!!\n");break; } } return 0; }
|