一、实验目的及要求
⒈理解二叉树的抽象数据类型的定义,及在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;
}