数据结构6 && 实验六:树的操作
2013-11-18 09:56
274 查看
一、实验目的及要求
⒈理解二叉树的抽象数据类型的定义,及在C语言环境中的表示方法。
⒉理解二叉树的基本操作的算法,及在C语言环境中一些主要基本操作的实现。
⒊在C语言环境下实现二叉树的应用操作:
①采用顺序存储创建一棵二叉树。
②采用二叉链表存储一棵二叉树,并实现二叉树的先序、中序、后序遍历的递归算法。
二、实验内容
经过对实验目的及要求的分析,本实验分为三个部分,分别为建立二叉树、实现二叉树的先序、中序、后序的递归算法及二叉树的中序的非递归算法。
⒈理解二叉树的抽象数据类型的定义,及在C语言环境中的表示方法。
⒉理解二叉树的基本操作的算法,及在C语言环境中一些主要基本操作的实现。
⒊在C语言环境下实现二叉树的应用操作:
①采用顺序存储创建一棵二叉树。
②采用二叉链表存储一棵二叉树,并实现二叉树的先序、中序、后序遍历的递归算法。
二、实验内容
经过对实验目的及要求的分析,本实验分为三个部分,分别为建立二叉树、实现二叉树的先序、中序、后序的递归算法及二叉树的中序的非递归算法。
#include<cstdio> #include<algorithm> #include<queue> using namespace std; const int maxnode = 100000; struct ArrayTree { int node[maxnode]; int num; void create() { int n; scanf("%d",&n); num = n; for(int i = 1 ; i <= n ; ++ i) { scanf("%d",node+i); } } void print() { for(int i = 1 ; i <= num ; ++ i) { printf(" %d",node[i]); } printf("\n"); } }; struct node { struct node* left; struct node* right; int value; }; struct BiTree { node* root; node* getnode() { node *child = (node*)malloc(sizeof(node)); scanf("%d",&child->value); child->left = NULL; child->right = NULL; return child; } void create() { int n; scanf("%d",&n); queue<node*> q; root = (node*)malloc(sizeof(node)); scanf("%d",&root->value); q.push(root); int i = 1; while(i<n) { node *rt = q.front(); q.pop(); rt->left = getnode(); q.push(rt->left); i++; if(i>=n) break; rt->right = getnode(); q.push(rt->right); i++; } } }; void pre_order(node* root) { if(root==NULL) return; printf(" %d", root->value); if(root->left!=NULL) pre_order(root->left); if(root->right!=NULL) pre_order(root->right); } void in_order(node* root) { if(root->left!=NULL) in_order(root->left); if(root != NULL) printf(" %d",root->value); if(root->right!=NULL) in_order(root->right); } void post_order(node* root) { if(root->left!=NULL) post_order(root->left); if(root->right!=NULL) post_order(root->right); if(root != NULL) printf(" %d",root->value); } int main() { freopen("in","r",stdin); ArrayTree tmp; tmp.create(); printf("\n顺序存储完全二叉树:"); tmp.print(); BiTree tree; tree.create(); printf("\n前序遍历二叉树:"); pre_order(tree.root); printf("\n中序遍历二叉树:"); in_order(tree.root); printf("\n后序遍历二叉树");post_order(tree.root); return 0; }
相关文章推荐
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构揭秘一
- Java数据结构之简单链表的定义与实现方法示例
- qqwry.dat的数据结构图文解释第1/2页
- Java数据结构之双端链表原理与实现方法
- Huffman 编码压缩算法
- C 的反思穷究链表
- 数据结构&算法学习
- 第二话:数据结构的历史与来由
- 第一话:你的数据结构怎么学的?
- 鸟瞰数据结构的知识点全貌
- 数据结构的基本概念和术语
- 开发语言、开发工具、数据结构和算法的关系
- 排序算法总结
- CC数据结构学习.0
- PHP常用函数
- [转]可视化的数据结构和算法
- PHP数据结构预热:PHP的迭代器
- C语言实现各类排序算法
- vector list两种不同的容器