本文测试例子的二叉树
//successful achievement
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
struct BinaryNode{
char ch; //显示字母
struct BinaryNode * lChild; //左孩子
struct BinaryNode * rChild; //右孩子
};
//递归函数,实现遍历
void recursion_preorder_traversal(struct BinaryNode * root){
//递归最重要的循环结束条件
if (root == NULL){ //碰到空就回退???大约07:08 代码在执行过程中,(小箭头)碰到空,就直接不管这行代码,不是说直接退出整个函数
return;
}
//先序遍历
//先根
printf("%c\n", root->ch);
//再左
recursion_preorder_traversal (root->lChild);
//再右
recursion_preorder_traversal (root->rChild);
}
//inorder
void recursion_inorder_traversal(struct BinaryNode * root){
if (root == NULL){
return;
}
recursion_inorder_traversal (root->lChild);
printf("%c\n",root->ch);
recursion_inorder_traversal (root->rChild);
}
//postorder
void recursion_postorder_traversal(struct BinaryNode * root){
if (root == NULL){
return;
}
recursion_postorder_traversal (root->lChild);
recursion_postorder_traversal (root->rChild);
printf("%c\n",root->ch);
}
void test01(){ //具体的树结构见文章开头
//建立节点
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 };
//建立节点之间的关系
nodeA.lChild = &nodeB; //因为等号左边是指针,所以右边需要取地址
nodeA.rChild = &nodeF;
nodeB.rChild = &nodeC;
nodeC.lChild = &nodeD;
nodeC.rChild = &nodeE;
nodeF.rChild = &nodeG;
nodeG.lChild = &nodeH;
//通过递归函数实现先序遍历
cout<<"preorder is at list:"<<endl;
recursion_preorder_traversal(&nodeA);
cout<<endl;
cout<<"inorder is at list:"<<endl;
recursion_inorder_traversal(&nodeA);
cout<<endl;
cout<<"postorder is at list:"<<endl;
recursion_postorder_traversal(&nodeA);
cout<<endl;
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}