二叉树递归遍历的简易实现


大家好这是我第一次用markdown工具写博客,本文主要提供了一个超级简单的c++实现二叉树遍历的算法举例, 有效代码也就50行左右

举例说明的二叉树代码

环境是c++,下面是我的代码,代码放入c++中即可运行

#include "pch.h"
#include <iostream>
#include <stdlib.h>
#include <string.h>
struct BinaryNode
{//数据域
    char ch;
    //指针域
    struct BinaryNode* lChild;
    struct BinaryNode* rChild;
};
//前序遍历
void recursionpreorder (struct BinaryNode * root) {
    if (root == nullptr)
        return;
    printf_s("%c ", root->ch);
    recursionpreorder(root->lChild);
    recursionpreorder(root->rChild);
}

//中序遍历
void recursionmidorder(struct BinaryNode * root) {
    if (root == nullptr)
        return;
    recursionmidorder(root->lChild);
    printf_s("%c ", root->ch);
    recursionmidorder(root->rChild);}
    //后续遍历
void recursionlastorder(struct BinaryNode * root) {
    if (root == nullptr)
        return;
    recursionlastorder(root->lChild);
    recursionlastorder(root->rChild);
    printf_s("%c ", root->ch);}
void test01() {
    struct BinaryNode nodeA = { 'A',nullptr,nullptr };
    struct BinaryNode nodeB = { 'B',nullptr,nullptr };
    struct BinaryNode nodeC = { 'C',nullptr,nullptr };
    struct BinaryNode nodeD = { 'D',nullptr,nullptr };
    struct BinaryNode nodeE = { 'E',nullptr,nullptr };
    struct BinaryNode nodeF = { 'F',nullptr,nullptr };
    struct BinaryNode nodeG = { 'G',nullptr,nullptr };
    struct BinaryNode nodeH = { 'H',nullptr,nullptr };
    //建立关系
    nodeA.lChild = &nodeB;
    nodeA.rChild = &nodeF;
    nodeB.lChild = &nodeC;
    nodeC.lChild = &nodeD;
    nodeC.rChild = &nodeE;
    nodeF.lChild = &nodeG;
    nodeG.lChild = &nodeH;
    printf_s("先序遍历的结果为:");
    recursionpreorder(&nodeA);
    printf_s("\r\n中序遍历的结果为:");
    recursionmidorder(&nodeA);
    printf_s("\r\n后序遍历的结果为:");
    recursionlastorder(&nodeA);
}
int main()
{
    test01();
    
}

我的二叉树长如图所示

在这里插入图片描述

测试结果

在这里插入图片描述
好了以上就是我全部博客的内容,完结撒花!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值