数据结构和算法----二叉树的四种遍历:

二叉树的四种遍历:

前序遍历,中序遍历,后序遍历,层序遍历

这里写图片描述

遍历顺序:

先序遍历:A → B → D → C
中序遍历:B → D → A → C
后续遍历:D → B → C → A
层序遍历:A → B → C → D

代码实现:

#include <iostream>
#include <cstdlib>
#include <queue>
using namespace std;

typedef struct node {
	char data;
	struct node *lChild, *rChild;
	node(char data_):data(data_),lChild(NULL), rChild(NULL){
	}
}treeNode, *TreeNode;

//简历二叉树
void  createTree(TreeNode &T) {
	char  ch;
	ch = getchar();
	if(ch == '#') {
		T = NULL;
	}
	else {
		T = new treeNode(ch);
		if (!T)
			exit(1);

		//cout <<T->data << ',';
		createTree(T->lChild);  //增加左子树
		createTree(T->rChild);  //增加右子树
	}
}

//二叉树前序遍历   根-> 左-> 右
void PreOrderTraverse(treeNode *T)
{
	if (!T)
		return;

	cout << T->data << ",";
	PreOrderTraverse(T->lChild);
	PreOrderTraverse(T->rChild);
}

//二叉树中序遍历   左-> 根-> 右
void InOrderTraverse(treeNode *T)
{
	if (!T)
		return;

	InOrderTraverse(T->lChild);
	cout << T->data << ",";
	InOrderTraverse(T->rChild);
}

//二叉树后序遍历   左-> 右-> 根
void PostOrderTraverse(treeNode *T)
{
	if (!T)
		return;

	PostOrderTraverse(T->lChild);
	PostOrderTraverse(T->rChild);
	cout << T->data << ",";
}

//层序遍历上下左右
void FloorPrint_QUEUE(treeNode *T)
{
	queue<treeNode*> queue;
	if (T)
	{
		queue.push(T);
	}

	while (!queue.empty())
	{
		treeNode *tmp = queue.front();
		cout << tmp->data << ",";

		if (tmp->lChild)
			queue.push(tmp->lChild);


		if (tmp->rChild)
			queue.push(tmp->rChild);

		queue.pop();
	}
}

int  main()
{
    //AB#D##C## 前序遍历创建二叉树
	cout << "创建二叉树:" << endl;
	treeNode* T = new treeNode(' ');
	createTree(T);
	cout << endl;

	cout << "前序遍历:" << endl;
	PreOrderTraverse(T);
	cout << endl;
	
	cout << "中序遍历:" << endl;
	InOrderTraverse(T);
	cout << endl;

	cout << "后续遍历:" << endl;
	PostOrderTraverse(T);
	cout << endl;

	cout << "层序遍历:" << endl;
	FloorPrint_QUEUE(T);
	cout << endl;

	getchar();
	return 0;
}

运行结果:

参考:

https://www.cnblogs.com/du001011/p/11229170.html

https://blog.csdn.net/m0_37925202/article/details/80796010

 https://blog.csdn.net/qq_37043100/article/details/80171535

猜你喜欢

转载自blog.csdn.net/weixin_39752599/article/details/106029470