#include #include #include #include #define MAX 100 int top = -1; typedef struct tnode { int data; struct tnode *lchild; struct tnode *rchild; }BTNode, *BTree; typedef struct Queue{ BTree data; struct Queue* next; }Qnode; typedef struct point{ Qnode* front;//头指针 Qnode* rear;//尾指针 }LinkQueue; BTree CreatBTree(){ int num; BTree p; scanf("%d", &num); if (num == -1) { p = NULL; } else { p = (BTree) malloc(sizeof(BTNode)); p->data = num; printf("请输入 %d 的左子树:\n", num); p->lchild = CreatBTree(); printf("请输入 %d 的右子树:\n", num); p->rchild = CreatBTree(); } return p; } void PreOrder(BTree tree){ if(tree == NULL){ return; } printf("%d", tree->data); PreOrder(tree->lchild); PreOrder(tree->rchild); } void InOrder(BTree tree){ if(tree == NULL){ return; } InOrder(tree->lchild); printf("%d", tree->data); InOrder(tree->rchild); } void LastOrder(BTree tree){ if(tree == NULL){ return; } LastOrder(tree->lchild); LastOrder(tree->rchild); printf("%d", tree->data); } void push(BTree a[],BTree node){ a[++top] = node; } void pop(){ if (top == -1) { return; } top--; } BTree getTop(BTree a[]){ return a[top]; } void InOrder2(BTree Tree){ top = -1; BTree a[MAX],p; push(a, Tree); while (top != -1) { while ((p = getTop(a)) && p != NULL){ push(a, p->lchild); } pop(); if (top != -1) { p = getTop(a); pop(); printf("%d", p->data); push(a, p->rchild); } } } void InitQueue(LinkQueue* q){ q->front = q->rear = (Qnode*)malloc(sizeof(Qnode)); if (q->front == NULL) return; } void EnQueue(LinkQueue* q, BTree ele){ Qnode* p = (Qnode*)malloc(sizeof(Qnode)); if (p == NULL) { return; } if (ele == NULL) return; p->data = ele; p->next = NULL; q->rear->next = p; q->rear = p; } int QueueEmpty(LinkQueue q) { if (q.front != q.rear) return 1; else return 0; } BTree DeQueue(LinkQueue* q) { if (q->front == q->rear){ return; } Qnode* p = q->front->next; BTree q_ = p->data; q->front->next = p->next; if (q->rear == p) q->rear = q->front; free(p); return q_; } void LevelOrder(BTree Tree){ top = -1; BTree p; LinkQueue Q1; InitQueue(&Q1); EnQueue(&Q1, Tree); while (QueueEmpty(Q1)) { p = DeQueue(&Q1); printf("%d ", p->data); if (p->lchild != NULL) { EnQueue(&Q1, p->lchild); } if (p->rchild != NULL) { EnQueue(&Q1, p->rchild); } } } int main(){ int choice; BTree tree; for(;;){ printf("\t\t1.递归先序建立二叉树\n"); printf("\t\t2.先序遍历二叉树\n"); printf("\t\t3.中序遍历二叉树\n"); printf("\t\t4.后序遍历二叉树\n"); printf("\t\t5.中序非递归遍历二叉树\n"); printf("\t\t6.层次遍历二叉树\n"); printf("\t\t0.退出\n"); printf("请选择:"); scanf("%d",&choice); if(choice==0) break; switch (choice) { case 1: printf("开始先序创建二叉树,输入 -1 为空节点\n"); tree = CreatBTree(); break; case 2: PreOrder(tree); printf("\n"); break; case 3: InOrder(tree); printf("\n"); break; case 4: LastOrder(tree); printf("\n"); break; case 5: InOrder2(tree); printf("\n"); break; case 6: LevelOrder(tree); printf("\n"); break; default: break; } printf("请按任意键继续..."); getch(); system("cls"); } printf("感谢使用,再见\n"); return 0; }