c++实现二叉树的先序遍历,中序遍历,后序遍历(递归方法)及运行实例结果

这是算法导论中二叉树搜索的一个题

二叉树如图所示


c++代码

#include<iostream>
#define N 7
using namespace std;

//定义节点
class node
{
public:
    int data;
    node *leftChild;//指针
    node *rightChild;
};
typedef node *BiTree;//等价

node *createNode(int value)//创建节点,返回类型指针型,所以加*
{
    node * q = new node;
    q->leftChild = NULL;//leftChild指针为空
    q->rightChild = NULL;
    q->data = value;

    return q;
}

BiTree createBiTree()
{
    node *p[N] = {NULL};
    int array[6]={6,5,7,2,5,8};//输入的二叉树
    for(int i=0;i<6;++i)
        p[i] = createNode(array[i]);
    for(int i = 0; i < N/2; i++)
    {
        p[i]->leftChild = p[i * 2 + 1];
        p[i]->rightChild = p[i * 2 + 2];
    }

    return p[0];
}
//访问节点中的数据
int visit(BiTree tree)
{
    return tree->data;
}
// 先序遍历
void preorderTreeWalk(BiTree tree)
{
    if(tree)
    {
        cout << visit(tree) << " ";
        preorderTreeWalk(tree->leftChild);
        preorderTreeWalk(tree->rightChild);
    }
}
// 中序遍历
void inorderTreeWalk(BiTree tree)
{
    if(tree)
    {
        inorderTreeWalk(tree->leftChild);
        cout << visit(tree) << " ";
        inorderTreeWalk(tree->rightChild);
    }
}
// 后序遍历
void postorderTreeWalk(BiTree tree)
{
    if(tree)
    {
        postorderTreeWalk(tree->leftChild);
        postorderTreeWalk(tree->rightChild);
        cout << visit(tree) << " ";
    }
}

int main()
{
    BiTree tree = createBiTree();
    cout << "先序遍历结果为:";
    preorderTreeWalk(tree);
    cout << endl;
    cout << "中序遍历结果为:";
    inorderTreeWalk(tree);
    cout << endl;
    cout << "后序遍历结果为:";
    postorderTreeWalk(tree);
    cout << endl;

    return 0;
}


运行结果




  • 5
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值