二叉树的前序、中序、后序、层序遍历

1.二叉树的结构

typedef int BTDataType;

typedef struct BinaryTreeNode
{
	BTDataType val;
	struct BinaryTreeNode* left;
	struct BinaryTreeNode* right;
}BTNode;

就比如如下结构: 

2.前序遍历 

手搓一棵树

BTNode* CreateTree2()
{
	BTNode* n1 = BuyNode(1);
	BTNode* n2 = BuyNode(2);
	BTNode* n3 = BuyNode(3);
	BTNode* n4 = BuyNode(4);
	BTNode* n5 = BuyNode(5);
	BTNode* n6 = BuyNode(6);

	n1->left = n2;
	n1->right = n4;
	n2->left = n3;
	n4->left = n5;
	n4->right = n6;
	return n1;
}

代码实现:

void PreOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("N ");
		return;
		
	}
	printf("%d ", root->val);

	PreOrder(root->left);
	PreOrder(root->right);
}

3.中序遍历 

代码实现:

void InOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("N ");
		return;
	}

	InOrder(root->left);
	printf("%d ", root->val);
	InOrder(root->right);
}

4.后序遍历 

代码实现:

void PostOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("N ");
		return;
	}

	PostOrder(root->left);
	PostOrder(root->right);
	printf("%d ", root->val);
}

5.层序遍历

层序遍历,顾名思义,就是一层一层遍历。这里就不用递归了,需要用到队列。

采取的思想是父亲带孩子的思想。

我们这里要用到队列,所以要有队列的程序。怎么把原先写好的代码放到二叉树的程序里呢?

按照以下顺序:

第一步:右击源文件,在添加里找到现有项,点击。

第二步:在所在文件夹里找到队列的文件夹

第三步:选中所要用到的,复制

第四步:回到原来的文件夹里,粘贴以上两个 Queue.c和Queue.h

第五步:将Queue.h移到头文件里,直接拖动就好

代码实现:

void LevelOrder(BTNode* root)
{
	Que q;
	QueueInit(&q);
	if (root)
	{
		QueuePush(&q, root);
	}

	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		QueuePop(&q);

		printf("%d ", front->val);

		if (front->left)
		{
			QueuePush(&q, front->left);
		}

		if (front->right)
		{
			QueuePush(&q, front->right);
		}
	}

	QueueDestory(&q);
}

 over~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值