二叉树先序遍历的实现思想是:
访问根节点;
访问当前节点的左子树;
若当前节点无左子树,则访问当前节点的右子树;
二叉树中序遍历的实现思想是:
访问当前节点的左子树;
访问根节点;
访问当前节点的右子树;
二叉树后序遍历的实现思想是:
从根节点出发,依次遍历各节点的左右子树,
直到当前节点左右子树遍历完成后,才访问该节点元素。
总结一点,所谓"前、中、后"指的是什么时候遍历根节点
#include<iostream>
using namespace std;
typedef struct BiNode
{
int iDate;
BiNode* pLeft, *pRight;
}STBiNode;
// 构建一颗树
void CreateTree(STBiNode* pTree);
// 打印节点信息
void PrintNodeInfo(STBiNode* pNode);
// 前序遍历
void PrePrintTree(STBiNode* pTree);
// 中序遍历
void MidPrintTree(STBiNode* pTree);
// 后序遍历
void PostPrintTree(STBiNode* pTree);
int main()
{
STBiNode *pTree = NULL;
pTree = (STBiNode*)malloc(sizeof(STBiNode));
CreateTree(pTree);
cout << "前序遍历" << endl;
PrePrintTree(pTree);
cout <<"中序遍历"<< endl;
MidPrintTree(pTree);
cout << "后序遍历" << endl;
PostPrintTree(pTree);
cin.get();
return 0;
}
void CreateTree(STBiNode* pTree)
{
//pTree = (STBiNode*)malloc(sizeof(STBiNode));
pTree->iDate = 1;
pTree->pLeft = (STBiNode*)malloc(sizeof(STBiNode));
pTree->pLeft->iDate = 2;
pTree->pRight = (STBiNode*)malloc(sizeof(STBiNode));
pTree->pRight->iDate = 3;
pTree->pLeft->pLeft = (STBiNode*)malloc(sizeof(STBiNode));
pTree->pLeft->pLeft->iDate = 4;
pTree->pLeft->pLeft->pLeft = NULL;
pTree->pLeft->pLeft->pRight = NULL;
pTree->pLeft->pRight = (STBiNode*)malloc(sizeof(STBiNode));
pTree->pLeft->pRight->iDate = 5;
pTree->pLeft->pRight->pLeft = NULL;
pTree->pLeft->pRight->pRight = NULL;
pTree->pRight->pLeft = (STBiNode*)malloc(sizeof(STBiNode));
pTree->pRight->pLeft->iDate = 6;
pTree->pRight->pLeft->pLeft = NULL;
pTree->pRight->pLeft->pRight = NULL;
pTree->pRight->pRight = (STBiNode*)malloc(sizeof(STBiNode));
pTree->pRight->pRight->iDate = 7;
pTree->pRight->pRight->pLeft = NULL;
pTree->pRight->pRight->pRight = NULL;
}
// 打印节点信息
void PrintNodeInfo(STBiNode* pNode)
{
int iCount = 0;
int iDate = pNode->iDate;
cout << "iSize ="<< iDate <<endl;
}
// 前序遍历
void PrePrintTree(STBiNode* pTree)
{
if(pTree)
{
PrintNodeInfo(pTree);
PrePrintTree(pTree->pLeft);
PrePrintTree(pTree->pRight);
}
}
// 中序遍历
void MidPrintTree(STBiNode* pTree)
{
if(pTree)
{
PrePrintTree(pTree->pLeft);
PrintNodeInfo(pTree);
PrePrintTree(pTree->pRight);
}
}
// 后序遍历
void PostPrintTree(STBiNode* pTree)
{
PrePrintTree(pTree->pLeft);
PrePrintTree(pTree->pRight);
PrintNodeInfo(pTree);
}