【数据结构】树的基本操作
要求:
熟悉树的基本定义,树的存储方式,建立方法及相关操作,能够根据实际情况选择合适的存储结构。
1、掌握树的遍历的基本操作
2、提交实验报告,报告内容包括:目的、要求、算法描述、程序结构、主要变量说明、程序清单、调试情况、设计技巧、心得体会。
以二叉链表作存储结构,试编写前序,中序,后序遍历二叉树算法
代码实现:
#include<stdio.h>
#include<stdlib.h>
#define BITREE_NODE_TYPE_ELEMENT chartypedef struct bi_tree_node
{BITREE_NODE_TYPE_ELEMENT data;struct bi_tree_node* LChild;struct bi_tree_node* RChild;
}BiTree_Node, * BiTree;void visit(BITREE_NODE_TYPE_ELEMENT data)
{putchar(data);
}void createBiTree(BiTree* bi_tree)
{char ch;ch = getchar();if (ch == '*')*bi_tree = NULL;else{*bi_tree = (BiTree)malloc(sizeof(BiTree_Node));(*bi_tree)->data = ch;createBiTree(&((*bi_tree)->LChild));createBiTree(&((*bi_tree)->RChild));}
}void preOrder(BiTree root1){if (root1 != NULL){visit(root1->data); preOrder(root1->LChild); preOrder(root1->RChild);}
}void inOrder(BiTree root2){if (root2 != NULL){inOrder(root2->LChild); visit(root2->data); inOrder(root2->RChild);}
}void postOrder(BiTree root3){if (root3 != NULL){postOrder(root3->LChild);postOrder(root3->RChild);visit(root3->data);}
}int main(){BiTree bi_tree = NULL;puts("请按照先序序列输入一棵二叉树的结点数据并用'*'来代表空值:");createBiTree(&bi_tree);printf("\n先序序列:");preOrder(bi_tree);printf("\n中序序列:");inOrder(bi_tree);printf("\n后序序列:");postOrder(bi_tree);putchar('\n');return 0;
}