C++使用递归的方法创建二叉树

本文介绍了一种使用C++实现二叉树的方法,并演示了如何通过递归方式完成前序、中序及后序遍历。文章提供了一个简单的程序实例,用于创建二叉树并展示不同类型的遍历结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
using namespace std;
typedef struct node               // 创建节点结构
{
    char data;
    struct node *lchild,*rchild;
}binary_tree,*tree;

void creat_tree(tree &t)          // 创建二叉树
{
    char ch;
    cin >> ch;
    if( ch == '0' )               // '0'表示没有子树
    {
        t = NULL;
    }
    else
    {
        t = (tree) new binary_tree;
        if(!t)
            exit(0);             //如果没成功申请空间 则退出
        t->data = ch;
        creat_tree( t->lchild );
        creat_tree( t->rchild );
    }
}
//前序遍历
void pre_travel(tree &t)        //前序遍历:根结点->左子树->右子树
{
 if(t)
 {
    cout << t->data;            //输出节点
    pre_travel( t->lchild );
    pre_travel( t->rchild );
 }
}

//中续遍历
void mid_travel( tree &t )   //中序遍历:左子树->根结点->右子树
{
 if(t)
 {  
    pre_travel(t->lchild);
    cout << t->data;          //输出节点
    pre_travel( t->rchild );
 }
}

//后续遍历
void post_travel(tree &t)   //中序遍历:左子树->右子树->根结点
{
 if(t)
 {  
    pre_travel( t->lchild ); 
    pre_travel( t->rchild );
    cout << t->data;      //输出节点
 }
}

int main()
{
    tree t;
    //"ab00c00"表示有三个节点,根节点a和它的左右孩子结点b,c,
    cout << "请输入二叉树节点:(例如输入:AB00C00)";
    creat_tree(t);

    cout << "先续遍历:";
    pre_travel(t);
    cout << endl;

    cout << "中续遍历:";
    mid_travel(t);
    cout << endl;

    cout << "后续遍历:";
    post_travel(t);
    cout << endl;

    system("pause");
    return 0;
}

本程序创建的二叉树如下:

这里写图片描述

若想创建以下二叉树,则需输入:ABD00E00C00
这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值