二叉树的三种遍历

//程序中创建的二叉树的直观图

三种输出结果

先跟 124567389

中跟 426571839

后跟 467528931

源代码:

#include<iostream>
using namespace std;
typedef struct tree{
    int data;
    tree* L=nullptr;
    tree* R=nullptr;
}tree,*T;

void fun1(T t){
    cout<<t->data;
    if(t->L!=nullptr){fun1(t->L);}
    if(t->R!=nullptr){fun1(t->R);}
    
}
void fun2(T t){
    
    if(t->L!=nullptr){fun2(t->L);}
    cout<<t->data;
    if(t->R!=nullptr){fun2(t->R);}
    
}
void fun3(T t){
    if(t->L!=nullptr){fun3(t->L);}
    if(t->R!=nullptr){fun3(t->R);}
    cout<<t->data;
}

int main(){
    //创建二叉树
    tree t1,t2,t3,t4,t5,t6,t7,t8,t9;
    t1.data = 1; t2.data = 2; t3.data = 3;   
    t4.data = 4; t5.data = 5; t6.data = 6;   
    t7.data = 7; t8.data = 8; t9.data = 9;  
    t1.R=&t3;
    t1.L=&t2;
    t2.L=&t4;
    t2.R=&t5;
    t5.L=&t6;
    t5.R=&t7;
    t3.L=&t8;
    t3.R=&t9;
    T t=&t1;
    //遍历输出
    fun1(t);cout<<endl;//先跟遍历
    fun2(t);cout<<endl;//中根遍历
    fun3(t);cout<<endl;//后跟遍历
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值