前序遍历,中序遍历,后序遍历(树的深度优先算法),层序遍历(树的广度优先算法)

#include <stdio.h>
#include <stdlib.h>
#include <queue>
using namespace std;
void preOrder(Node *node)
{
	if(node==NULL) return;
	printf("%d",node->k);
	preOrder(node->l);
	preOrder(node->r);
}

void inOrder(Node *node)
{
	if(node==NULL) return;
	preOrder(node->l);
	printf("%d",node->k);
	preOrder(node->r);
}

void postOrder(Node *node)
{
	if(node==NULL) return;
	preOrder(node->l);
	preOrder(node->r);
	printf("%d",node->k);
}

void layerOrder()
{
	queue<Node*> q;
	q.push(root);
	while(!q.empty())
	{
		Node *n=q.front();
		q.pop();
		printf("%d",n->k);
		if(n->l!=NULL) q.push(n->l);
		if(n->r!=NULL) q.push(n->r);
	}
}

void main()
{
	int i;
	root=NULL;
	for(i=3;i<5;i++) insert1(i,'A'+i);
	for(i=0;i<3;i++) insert1(i,'A'+i);
	for(i=5;i<10;i++) insert1(i,'A'+i);
	printf("\n------前序遍历------\n");
	preOrder(root);
	printf("\n------中序遍历------\n");
	inOrder(root);
	printf("\n------后序遍历------\n");
	postOrder(root);
	printf("\n------层序遍历------\n");
	layerOrder();
	printf("\n");
}

posted @ 2018-05-04 12:16  王雪亮  阅读(447)  评论(0编辑  收藏  举报