Simple realization of recursive traversal of binary tree
Hello, everyone. This is the first time I use markdown to write a blog. This article mainly provides an example of a super simple C++ algorithm for implementing binary tree traversal. The effective code is only about 50 lines .
Illustrated binary tree code
The environment is c++, the following is my code, the code can run in 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();
}
My binary tree is as long as the picture
Test Results
Alright, the above is the content of all my blogs.