【二叉树的遍历】
二叉树的遍历方式有四种: 前序遍历,中序遍历,后序遍历,层次遍历。其中前三种遍历方式二叉树常用的遍历方式。
【代码实现遍历】
当实现二叉树的遍历时,递归是实现前序遍历,中序遍历与后序遍历的最简单的方式,因为树的结构本身就是一种层次上不同,但结构是一致的,利用递归思想写出的代码简洁易懂。
// 二叉树三种遍历递归实现
#include<stdio.h>
#include<stdlib.h>
// 定义二叉树结构
typedef struct BTNode {
char data;
struct BTNode* pLchild;
struct BTNode* pRchild;
}BTNode, *BTree;
// 创建一棵二叉树
BTree create_tree();
// 二叉树前序遍历
void pre_traverse(BTree);
// 二叉树中序遍历
void in_traverse(BTree);
// 二叉树后序遍历
void beh_traverse(BTree);
BTree create_tree() {
// 创建树的节点
BTree pA = (BTree)malloc(sizeof(BTNode));
BTree pB = (BTree)malloc(sizeof(BTNode));
BTree pC = (BTree)malloc(sizeof(BTNode));
BTree pD = (BTree)malloc(sizeof(BTNode));
BTree pE = (BTree)malloc(sizeof(BTNode));
BTree pF = (BTree)malloc(sizeof(BTNode));
// BTree pA = (BTree)malloc(sizeof(BTNode));
pA->data = 'A';
pB->data = 'B';
pC->data = 'C';
pD->data = 'D';
pE->data = 'E';
pF->data = 'F';
pA->pLchild = pB;
pA->pRchild = pC;
pB->pLchild = pD;
pB->pRchild = pE;
pD->pLchild = pD->pRchild = NULL;
pE->pLchild = pE->pRchild = NULL;
pC->pLchild = pF;
pC->pRchild = NULL;
pF->pLchild = pF->pRchild = NULL;
return pA;
}
//前序遍历的递归实现
void pre_traverse(BTree pTree) {
if (pTree) {
printf("%c ", pTree->data);
if (pTree->pLchild)
pre_traverse(pTree->pLchild);
if (pTree->pRchild)
pre_traverse(pTree->pRchild);
}
}
// 中序遍历递归实现
void in_traverse(BTree pTree) {
if (pTree) {
if (pTree->pLchild)
in_traverse(pTree->pLchild);
printf("%c ", pTree->data);
if (pTree->pRchild)
in_traverse(pTree->pRchild);
}
}
// 后序遍历的递归实现
void beh_traverse(BTree pTree) {
if (pTree) {
if (pTree->pRchild)
beh_traverse(pTree->pRchild);
if (pTree->pLchild)
beh_traverse(pTree->pLchild);
printf("%c ", pTree->data);
}
}
int main() {
BTree pTree = create_tree();
printf("递归实现树的前序遍历: \n");
pre_traverse(pTree);
printf("\n");
printf("递归实现树的中序遍历: \n");
in_traverse(pTree);
printf("\n");
printf("递归实现树的后序遍历: \n");
beh_traverse(pTree);
printf("\n");
printf("hello world\n");
system("pause");
}