二叉树的前序,中序,后序遍历

二叉树先序遍历的实现思想是:
访问根节点;
访问当前节点的左子树;
若当前节点无左子树,则访问当前节点的右子树;

二叉树中序遍历的实现思想是:
访问当前节点的左子树;
访问根节点;
访问当前节点的右子树;

二叉树后序遍历的实现思想是:
从根节点出发,依次遍历各节点的左右子树,
直到当前节点左右子树遍历完成后,才访问该节点元素。

总结一点,所谓"前、中、后"指的是什么时候遍历根节点

#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);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值