二叉树的前中后序非递归(复习)

注意:不是二叉排序树,只是普通的二叉树。

相信二叉树的递归遍历对于很多人来说是很容易的,但这里要复习下非递归的实现。

前序和中序的非递归遍历相对容易一些,前序是从根到左子树不停的访问然后入栈,等左子树遍历到空时,出栈,再指向它的右子树,按照之前的规律入栈,一直执行。。。而中序略微变化一下,在入栈时先不访问,出栈时对对应结点进行访问。

后序访问也参考前两种解法,但注意根是最后访问的,所以如果第一次出栈,先访问它的右结点,再进栈,第二次出栈时直接访问结点本身,不再入栈。代码如下:

#include<iostream>
#include <stdio.h>
#include<stack>
#include <queue>
using namespace std;
//复习:非递归的二叉树前中后序遍历

struct BSTree{
	int value;
	BSTree* left;
	BSTree* right;
};

struct Node{
	BSTree* tree;
	bool first;
};

BSTree* CreateTree(){
	BSTree *t;
	int x;
	cin>>x;
	if(x == 0)
		t = NULL;
	else{
		t = new BSTree();
		t->value =x;
		printf("输入%d点的左孩子\n",x);
		t->left = CreateTree();
		printf("输入%d点的右孩子\n",x);
		t->right= CreateTree();
	}
	return t;
}

void printfTree(BSTree * root){
	if(root == NULL)
		return;
	queue<BSTree *> Queue;
	BSTree *temp;
	Queue.push(root);
	while(!Queue.empty()){
		temp = Queue.front();
		Queue.pop();
		cout<<" "<<temp->value;
		if(temp->left)
			Queue.push(temp->left);
		if(temp->right)
			Queue.push(temp->right);
	}
	cout<<endl;
}

void preorder(BSTree *root){
	if(root == NULL)
		return;
	stack<BSTree *> s;
	while(root || !s.empty()){
		while(root){
			cout<<" "<<root->value;
			s.push(root);
			root = root->left;
		}
		if(!s.empty()){
			root = s.top();
			s.pop();
			root = root->right;
		}
	}
}

void midorder(BSTree *root){
	if(root == NULL)
		return;
	stack<BSTree *> s;
	while(root || !s.empty()){
		while(root){
			s.push(root);
			root = root->left;
		}
		if(!s.empty()){
			root = s.top();
			s.pop();
			cout<<" "<<root->value;
			root = root->right;
		}
	}
}

void postorder(BSTree *root){
	if(root == NULL)
		return;
	stack<BSTree *> s;
	bool tag[20];
	while(root || !s.empty()){
		while(root){
			tag[root->value] = true;
			s.push(root);
			root = root->left;
		}
		if(!s.empty()){
			root = s.top();
			s.pop();
			if(tag[root->value] == true){
				tag[root->value] = false;
				s.push(root);
				root = root->right;
			}
			else if(tag[root->value] == false){
				cout<<" "<<root->value;
				root = NULL;
			}
		}
	}
}

int main(){
	BSTree *root = CreateTree();
	cout<<"树的层次遍历序列为:"<<endl;
	printfTree(root);
	cout<<"前序的遍历序列为:"<<endl;
	preorder(root);
	cout<<endl;
	cout<<"中序的遍历序列为:"<<endl;
	midorder(root);
	cout<<endl;
	cout<<"后序的遍历序列为:"<<endl;
	postorder(root);
	cout<<endl;
	system("PAUSE");
	return 0;
}
建立的树图示如下:


测试结果如下图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值