#include<stdio.h> #include<malloc.h> #include<process.h> #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define MAX_TREE_SIZE 100 typedef int Status; typedef int TElemType; TElemType Nil = 0; typedef TElemType SqBiTree[MAX_TREE_SIZE]; Status visit(TElemType e) { printf("%d ", e); return OK; } Status InitBiTree(SqBiTree T) { int i; for (i = 0; i < MAX_TREE_SIZE; i++) T[i] = Nil; return OK; } Status CreateBiTree(SqBiTree T) { int i = 0; printf(" 按层创建二叉树 "); printf("请按层序输入结点的值(整型) 0表示空结点,空格隔开,输999结束。结点数≤%d: ", MAX_TREE_SIZE); while (1) { scanf_s("%d", &T[i]); if (T[i] == 999) break; if (i != 0 && T[(i + 1) / 2 - 1] == Nil && T[i] != Nil) { printf("出现无双亲的非根结点%d ", T[i]); exit(ERROR); } i++; } while (i < MAX_TREE_SIZE) { T[i] = Nil; i++; } return OK; } Status BiTreeEmpty(SqBiTree T) { if (T[0] == Nil) return TRUE; else return FALSE; } int BiTreeDepth(SqBiTree T) { int i, j = -1; for (i = MAX_TREE_SIZE - 1; i >= 0; i--) if (T[i] != Nil) break; i++; do j++; while (i >= pow(2, j)); return j; } Status Root(SqBiTree T, TElemType *e) { if (BiTreeEmpty(T)) return ERROR; else { *e = T[0]; return OK; } } Status(*VisitFunc)(TElemType); void PreTraverse(SqBiTree T, int e) { VisitFunc(T[e]); if (T[2 * e + 1] != Nil) PreTraverse(T, 2 * e + 1); if (T[2 * e + 2] != Nil) PreTraverse(T, 2 * e + 2); } Status PreOrderTraverse(SqBiTree T, Status(*Visit)(TElemType)) { VisitFunc = Visit; if (!BiTreeEmpty(T)) PreTraverse(T, 0); printf(" "); return OK; } void InTraverse(SqBiTree T, int e) { if (T[2 * e + 1] != Nil) InTraverse(T, 2 * e + 1); VisitFunc(T[e]); if (T[2 * e + 2] != Nil) InTraverse(T, 2 * e + 2); } Status InOrderTraverse(SqBiTree T, Status(*Visit)(TElemType)) { VisitFunc = Visit; if (!BiTreeEmpty(T)) InTraverse(T, 0); printf(" "); return OK; } void PostTraverse(SqBiTree T, int e) { if (T[2 * e + 1] != Nil) PostTraverse(T, 2 * e + 1); if (T[2 * e + 2] != Nil) PostTraverse(T, 2 * e + 2); VisitFunc(T[e]); } Status PostOrderTraverse(SqBiTree T, Status(*Visit)(TElemType)) { VisitFunc = Visit; if (!BiTreeEmpty(T)) PostTraverse(T, 0); printf(" "); return OK; } void LevelOrderTraverse(SqBiTree T, Status(*Visit)(TElemType)) { int i = MAX_TREE_SIZE - 1, j; while (T[i] == Nil) i--; for (j = 0; j <= i; j++) if (T[j] != Nil) Visit(T[j]); printf(" "); } void main() { Status i; TElemType e; SqBiTree T, s; printf(" "); printf("--------------------------------"); printf(" 电科一班陈辉作品 "); printf("---------------------------------- "); InitBiTree(T); CreateBiTree(T); printf(" 树的深度=%d ",BiTreeDepth(T)); i = Root(T, &e); if (i) printf(" 二叉树的根为:%d ", e); else printf("树空,无根 "); printf(" 先序遍历二叉树: "); PreOrderTraverse(T, visit); printf(" 中序遍历二叉树: "); InOrderTraverse(T, visit); printf(" 后序遍历二叉树: "); PostOrderTraverse(T, visit); printf(" 层序遍历二叉树: "); LevelOrderTraverse(T, visit); }