二叉树的递归遍历
//
// Created by KKONE on 2022/3/17.
//
#include <iostream>
#include <string>
using namespace std;
struct BinaryNode {
//数据域
char ch;
//指针域
struct BinaryNode *lChild; //定义一个左孩子
struct BinaryNode *rChild; //定义一个右孩子
};
//遍历
void recursion(struct BinaryNode *root) {
if (root == NULL) {
return;
}
//先序遍历
cout << root->ch << " ";
recursion(root->lChild);
recursion(root->rChild);
}
//创建一个实体类
void test() {
struct BinaryNode nodeA = {'A', NULL, NULL};
struct BinaryNode nodeB = {'B', NULL, NULL};
struct BinaryNode nodeC = {'C', NULL, NULL};
struct BinaryNode nodeD = {'D', NULL, NULL};
struct BinaryNode nodeE = {'E', NULL, NULL};
struct BinaryNode nodeF = {'F', NULL, NULL};
struct BinaryNode nodeG = {'G', NULL, NULL};
struct BinaryNode nodeH = {'H', NULL, NULL};
//建立tree
nodeA.lChild = &nodeB;
nodeA.rChild = &nodeF;
nodeB.lChild = &nodeC;
nodeC.lChild = &nodeD;
nodeC.rChild = &nodeE;
nodeF.rChild = &nodeG;
nodeG.lChild = &nodeH;
recursion(&nodeA);
}
int main() {
test();
return 0;
}