首页 > 学院 > 开发设计 > 正文

遍历二叉树

2019-11-06 06:31:17
字体:
来源:转载
供稿:网友
//#include <iostream>//using namespace std;#include <stdio.h>#include <stdlib.h>struct BTNode{	int data;	struct BTNode *pLchild;	struct BTNode *PRchild;};struct BTNode *CreateBTree(void);void PreTraverseBTree(struct BTNode *pT);void InTraverseBTree(struct BTNode *pT);void PostTraverseBTree(struct BTNode *pT);struct BTNode *CreateBTree(void){	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 = pB->pRchild = NULL;	pC->pLchild = pD;	pC->pRchild = NULL;	pD->pLchild = NULL;	pD->pRchild = pE;	pE->pLchild = pE->pRchild = NULL;	return pA;}void PreTraverseBTree(struct BTNode *pT){	if (NULL != pT)	{		printf("%c/n", pT->data);		if (NULL != pT->pLchild)PreTraverseBTree(pT->pLchild);//左子树递归		if (NULL != pT->pRchild)PreTraverseBTree(pT->pRchild);//右子树递归	}}void InTraverseBTree(struct BTNode *pT)//左-根-右{	if (NULL != pT)	{		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)	{		if (NULL != pT->pLchild)PostTraverseBTree(pT->pLchild);		if (NULL != pT->pRchild)PostTraverseBTree(pT->pRchild);		printf("%c/n", pT->data);	}}int main(){	struct BTNode *pT = CreateBTree();	PreTraverseBTree(pT);	InTraverseBTree(pT);	PostTraverseBTree(pT);	return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表