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


大家好这是我第一次用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();
    
}

我的二叉树长如图所示

在这里插入图片描述

测试结果

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

猜你喜欢

转载自blog.csdn.net/godgreen/article/details/109426320