数据结构6 && 实验六:树的操作

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




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值