链式二叉树和递归输出

include <stdio.h>

include <malloc.h>

struct BTNode
{
char data;
struct BTNode * pLchild; // p是指针 L是左 child是孩子
struct BTNode * pRchild;
};

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 = 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 (pT != NULL)
{
printf("%c ", pT->data);
if (NULL != pT->pLchild)
PreTraverseBTree(pT->pLchild);
if (NULL != pT->pRchild)
PreTraverseBTree(pT->pRchild);
}
}

void InTraverseBTree(struct BTNode * pT)
{
if (pT != NULL)
{
if (NULL != pT->pLchild)
InTraverseBTree(pT->pLchild);

	printf("%c ", pT->data);
	
	if (NULL != pT->pRchild)
		InTraverseBTree(pT->pRchild);
}

}

void PostTraverseBTree(struct BTNode * pT)
{
if (pT != NULL)
{
if (NULL != pT->pLchild)
InTraverseBTree(pT->pLchild);

	if (NULL != pT->pRchild)
		InTraverseBTree(pT->pRchild);

	printf("%c ", pT->data);
}

}

int main()
{
struct BTNode * pT = createBTree(); // 二叉树造好

printf("先序遍历的结果是:");
PreTraverseBTree(pT);
printf("\n");

printf("中序遍历的结果是:");
InTraverseBTree(pT);
printf("\n");

printf("后序遍历的结果是:");
PostTraverseBTree(pT);
printf("\n");

return 0;

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值