二叉树的存储和遍历,先序遍历,中序遍历,后序遍历

cpp代码实现

#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;
int n;

typedef struct BiNode
{
    int data;
    BiNode* lchild;
    BiNode* rchild;
    
}Bitree;

void Bitree_creat(Bitree* fa,int u)
{
    if(u > n) return;
    
    Bitree* l = new(BiNode);
    Bitree* r = new(BiNode);
    cin >> (fa->data);
    fa -> lchild = l;
    fa -> rchild = r;
    //cout << "Yes" << endl;
 //   cout << (fa ->data) << endl;
    
    Bitree_creat(fa ->lchild,2*u);
    Bitree_creat(fa ->rchild,2*u+1);
    return;
}

void Bitree_pr_pr(Bitree* fa,int u)
{
    if(u > n)return;
    //cout << "YES" << endl;
    cout << (fa ->data) << ' ';
    Bitree_pr_pr(fa ->lchild,u*2);
    Bitree_pr_pr(fa ->rchild,u*2+1);
    return;
}

void Bitree_center_pr(Bitree* fa,int u)
{
    if(u > n)return;
    
    Bitree_center_pr(fa ->lchild,u * 2);
    cout << (fa -> data) << ' ';
    Bitree_center_pr(fa ->rchild,u * 2 + 1);
    return;
}

void Bitree_en_pr(Bitree* fa,int u)
{
    if(u > n)return;
    
    Bitree_en_pr(fa ->lchild,u * 2);
    Bitree_en_pr(fa ->rchild,u * 2 + 1);
    cout << (fa -> data) << ' ';
    return;
}


int main()
{
    Bitree* T;T = new(BiNode);
    cin >> n;
    Bitree_creat(T,1);
    cout << "先序建立二叉树完成!" << endl;
    cout << "先序遍历:"<< endl;
    Bitree_pr_pr(T,1);
    cout << endl;
    cout << "中序遍历:"<< endl;
    Bitree_center_pr(T,1);
    cout << endl;
    cout << "后序遍历:"<< endl;
    Bitree_en_pr(T,1);
    cout << endl;
    
}


测试数据

20
1 2 3 4 5 
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20

运行结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值