//树的创建--井号法创建树 #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct _TreeNode{ char data; struct _TreeNode * leftchild; struct _TreeNode * rightchild; }TreeNode, *TreeNodePointer; /* 单纯的先序遍历结果,中序遍历结果,后序遍历结果都无法还原一棵二叉树, 必须用中序结果+先序结果---或者中序结果+后序结果 两两结合才能还原一棵树 井号法创建树思想: 将一个树所有的结点都补成二叉,没有节点的地方用#代替,用先序遍历的结果还原一棵二叉树 */ //创建树 TreeNodePointer CreateTree(){ char ch = 0; printf("请输入该结点的数据 "); scanf("%c", &ch); getchar(); if (ch == '#') { return NULL; } //创建根节点 TreeNodePointer root = (TreeNodePointer)malloc(sizeof(TreeNode)); //初始化 memset(root, 0, sizeof(TreeNode)); //结点赋值 root->data = ch; root->leftchild = CreateTree(); root->rightchild = CreateTree(); return root; } //销毁树--后序遍历销毁(结点删除了怎么找左子树,右子树啊) void DestroyTree(TreeNodePointer *root){ if (root == NULL) { printf("传入参数不可以为空! "); return; } TreeNodePointer temp = *root; //销毁左子树 if (temp->leftchild!=NULL) { DestroyTree(&temp->leftchild); } //销毁右子树 if (temp->rightchild!=NULL) { DestroyTree(&temp->rightchild); } //销毁根结点 free(temp); temp = NULL; *root = NULL; } //中序遍历树 void Inoder(TreeNodePointer root){ if (root==NULL) { printf("传入参数不可以空! "); return; } //遍历左子树 if (root->leftchild!=NULL) { Inoder(root->leftchild); } //遍历根结点 printf("%c", root->data); //遍历右子树 if (root->rightchild != NULL) { Inoder(root->rightchild); } } void main(){ //创建树 TreeNodePointer root=CreateTree(); //遍历树 Inoder(root); //销毁树 DestroyTree(&root); system("pause"); }