在这主要针对链式二叉树的创建和三种遍历(先序遍历、中序遍历和后序遍历)
此代码是在VS2010中运行可以通过的。
#include "stdafx.h"
#include<iostream>
using namespace std;
struct BTNode
{
char data;//数据域
struct BTNode*pLchild;//p是指针L是左,child是孩子
struct BTNode*pRchild;//
};
void PreTraverseBTree(struct BTNode*pT);
void InTraverseBTree(struct BTNode*pT);
void PostTraverseBTree(struct BTNode*pT);
struct BTNode *CreateBTree(void);
int _tmain(int argc, _TCHAR* argv[])
{
struct BTNode*pT=CreateBTree();
PreTraverseBTree(pT);
InTraverseBTree(pT);
PostTraverseBTree(pT);
system("pause");
return 0;
}
void PreTraverseBTree(struct BTNode*pT)
{
/*为算法
先访问根节点
再先序访问左子树
再先序访问右子树*/
if(pT!=NULL)
{
printf("%c\n", pT->data);
if(NULL!=pT->pLchild)
{
PreTraverseBTree(pT->pLchild);
}
if(NULL!=pT->pRchild)
{
PreTraverseBTree(pT->pRchild);
}
}
//pT->pLchild可以代表整个左子树
//pT->pLchild代表整个右子树
//递归既浪费空间,又浪费时间
}
void InTraverseBTree(struct BTNode*pT)
{
/*中序遍历伪算法:
先中序遍历访问左子树
访问根节点
再中序遍历访问右子树
*/
if(pT!=NULL)
{
if(NULL!=pT->pLchild)
{
InTraverseBTree(pT->pLchild);
}
printf("%c\n",pT->data);
if(NULL!=pT->pRchild)
{
InTraverseBTree(pT->pRchild);
}
}
}
void PostTraverseBTree(struct BTNode*pT)
{
/*后序遍历伪算法:
先中序遍历访问左子树
再中序遍历访问右子树
访问根节点
*/
if(NULL!=pT->pLchild)
{
PostTraverseBTree(pT->pLchild);
}
if(NULL!=pT->pRchild)
{
PostTraverseBTree(pT->pRchild);
}
printf("%c\n",pT->data);
}
struct BTNode *CreateBTree()
{
struct BTNode*pA=(struct BTNode*)malloc(sizeof(struct BTNode));
struct BTNode*pB=(struct BTNode*)malloc(sizeof(struct BTNode));
struct BTNode*pC=(struct BTNode*)malloc(sizeof(struct BTNode));
struct BTNode*pD=(struct BTNode*)malloc(sizeof(struct BTNode));
struct BTNode*pE=(struct BTNode*)malloc(sizeof(struct BTNode));
pA->data='A';
pB->data='B';
pC->data='C';
pD->data='D';
pE->data='E';
pA->pLchild=pB;
pA->pRchild=pC;
pB->pLchild=NULL;
pB->pRchild=NULL;
pC->pLchild=pD;
pC->pRchild=NULL;
pD->pLchild=NULL;
pD->pRchild=pE;
pE->pLchild=pE->pRchild=NULL;
return pA;
}