码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的遍历,递归,迭代,层序,中序,前序,后序

时间:2015-08-16 10:44:47      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
struct node{
	int key;
	node *left, *right;
};
void insertTree(node* &root,int val)
{
	node* tmp = (node*)malloc(sizeof(node));
	tmp->key = val;
	tmp->left = tmp->right = NULL;
	node *q = NULL, *p = root;
	while (p){
		q = p;
		if (p->key > val) p = p->left;
		else if (p->key < val) p = p->right;
		else return;
	}
	if (q == NULL) root = tmp;
	else if (q->key > val) q->left = tmp;
	else q->right = tmp;
}

//非递归遍历
//层序遍历
void printByLevel(node *root)
{
	node *p;
	queue<node*> q;
	q.push(root);
	while (!q.empty()){
		p = q.front(); q.pop();
		if (p){
			printf("%d ", p->key);
			q.push(p->left);
			q.push(p->right);
		}
	}
	printf("\n");
}
//中序遍历
void printByInorder(node* root)
{
	stack<node*> s;
	node *p = root;
	while (p || !s.empty()){
		while (p){
			s.push(p);
			p = p->left;
		}
		if (!s.empty()){
			p = s.top(); s.pop();
			printf("%d ", p->key);
			p = p->right;
		}
	}
	printf("\n");
}
//前序遍历
void printByPreorder(node* root)
{
	stack<node*> s;
	node* p = root;
	while (p||!s.empty()){
		while (p){
			printf("%d ", p->key);
			s.push(p);
			p = p->left;
		}
		if (!s.empty()){
			p = s.top(); s.pop();
			p = p->right;
		}
	}
	printf("\n");
}
//后序遍历
void printByPostorder(node *root)
{
	stack<node*> s;
	node* p = root;
	while (p || !s.empty()){
		while (p){
			printf("%d ", p->key);
			s.push(p);
			p = p->right;
		}
		if (!s.empty()){
			p = s.top(); s.pop();
			p = p->left;
		}
	}
	printf("\n");
}

//递归遍历
void inorder(node* root)
{
	if (root){
		inorder(root->left);
		printf("%d ", root->key);
		inorder(root->right);
	}
}
void preorder(node* root){
	if (root){
		printf("%d ", root->key);
		preorder(root->left);
		preorder(root->right);
	}
}
void postorder(node* root)
{
	if (root){
		postorder(root->left);
		postorder(root->right);
		printf("%d ", root->key);
	}
}
int main()
{
	node *root = NULL;
	int a[] = { 8, 4, 12, 2, 6, 10, 14, 3, 5, 7, 13 };
	for (int i = 0; i < 11; ++i)
		insertTree(root, a[i]);
	printf("Recursive Traversal : inorder preorder postorder\n");
	inorder(root);
	printf("\n");
	preorder(root);
	printf("\n");
	postorder(root);
	printf("\n");

	printf("Iteration Traversal : level inorder preorder postorder\n");
	printByLevel(root);
	printByInorder(root);
	printByPreorder(root);
	printf("Postorder Traversal print in reverse: ");
	printByPostorder(root);
}

  

对于后序遍历的非递归实现,该程序中是以相反的方向输出的,可以使用vector,实现正确方向。

二叉树的遍历,递归,迭代,层序,中序,前序,后序

标签:

原文地址:http://www.cnblogs.com/jokoz/p/4733679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!