//树的创建--井号法创建树 #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("请输入该结点的数据\n"); 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("传入参数不可以为空!\n"); 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("传入参数不可以空!\n"); 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"); }
数据结构 树的创建(井号法)
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
上一篇:数据结构 树的创建(先序+中序)
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
【数据结构】二叉树的存储结构
【数据结构】第五章——树与二叉树详细介绍二叉树的存储结构……
二叉树 数据结构 C语言 -
【数据结构】C语言实现二叉树
【数据结构】第五章——树与二叉树详细介绍如何通过C语言实现二叉树……
数据结构 C语言 二叉树 BST -
井号法创建二叉树
井号法创建二叉树.C#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>#include<stdlib.h>//
井号法创建二叉树 二叉树 C语言 数据结构 C语言进阶 -
数据结构--树
数据结构--树
js+css 数据结构--树 -
数据结构: 树
树存储方式能提高数据存储,读取的效率.
子树 二叉树 前序遍历 后序遍历 中序遍历