#include <stdio.h> #include <stdlib.h> #include <time.h> //二叉树的建立,搞个指针去维护要建立的树 typedef struct Tree { int data; struct Tree* lchild; struct Tree* rchild; }tree, * Tree; void Test(); void menu(); int TreeDepth(Tree T); void Create_Tree(Tree* T); void DestroyTree(Tree* T); void PreOrderTree(Tree T); void MidOrderTree(Tree T); void AftOrderTree(Tree T); int main() { Test(); return 0; } //不用管,工程里的东西 #include "该死的二叉树.h" //这么搞看着方便 void Test() { //后面rand()的初始条件,就这么用就ok srand((unsigned int)time(NULL)); //传二级指针,因为要树本身就是一级的,要改变树,传二级 Tree shift; Create_Tree(&shift); //求树的深度 printf("树的深度为:-> %d\n", TreeDepth(shift)); //这里的三个遍历一个道理,都是递归,代码顺序不同而已 printf("前序遍历二叉树\n"); PreOrderTree(shift); printf("中序遍历二叉树\n"); MidOrderTree(shift); printf("后序遍历二叉树\n"); AftOrderTree(shift); //树的销毁 DestroyTree(&shift); printf("全部销毁完毕!\n"); } //搞个菜单,方便看 void menu() { //注意二叉树怎么建立,N就返回双亲再选Y才建立右树 printf("是否建树?\n"); printf("*******************************\n"); printf("******Y.左子树 N.右子树******\n"); printf("*******************************\n"); } void Create_Tree(Tree* T) { //命令 char command; menu(); scanf("%c", &command); getchar(); if (command == 'N') { *T = NULL; return; } else { //用*T来维护开出的新空间 *T = (Tree)malloc(sizeof(tree)); (*T)->data = rand() % 66 + 1; (*T)->lchild = NULL; (*T)->rchild = NULL; //递归建树 printf("建立左子树\n"); Create_Tree(&((*T)->lchild)); printf("建立右子树\n"); Create_Tree(&((*T)->rchild)); } //右树建立完退出 return; } void DestroyTree(Tree* T) { if (*T != NULL) { //这里注意函数要传的是二级指针,所以递归时别忘了传二级 if ((*T)->lchild != NULL) { DestroyTree(&((*T)->lchild)); } if ((*T)->rchild != NULL) { DestroyTree(&((*T)->rchild)); } free(*T); *T = NULL; } printf("销毁!\n"); return; } void PreOrderTree(Tree T) { if (T) { printf("data = %2d lchild = %p rchild = %p\n", T->data, T->lchild, T->rchild); PreOrderTree(T->lchild); PreOrderTree(T->rchild); } } void MidOrderTree(Tree T)//递归 { if (T) { PreOrderTree(T->lchild); printf("data = %2d lchild = %p rchild = %p\n", T->data, T->lchild, T->rchild); PreOrderTree(T->rchild); } } void AftOrderTree(Tree T)//递归 { if (T) { PreOrderTree(T->lchild); PreOrderTree(T->rchild); printf("data = %2d lchild = %p rchild = %p\n", T->data, T->lchild, T->rchild); } } int TreeDepth(Tree T) { if (T == NULL) return 0; //这里画个图就出来了,两句说不清楚 int depth = 0; int ldepth = TreeDepth(T->lchild); int rdepth = TreeDepth(T->rchild); depth = ldepth > rdepth ? ldepth + 1 : rdepth + 1; return depth; }