二叉树的非递归遍历实现

#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <string.h>
using namespace std;
const int maxn = 2e5+32;
#define LL long long
const int inf = 0x3f3f3f3f;

struct Tree
{
	int val;
	Tree *left,*right;
	Tree(int v,Tree *l,Tree *r):val(v),left(l),right(r){}
};

unordered_map<Tree*,int>flag;


void preOrder(Tree* root)
{
	stack<Tree*> q;
	while(root!=NULL||!q.empty())
	{
		if(root!=NULL){

			q.push(root);
			cout<<root->val;
			root=root->left;
		}else{
			root=q.top()->right;
			q.pop();
		}
	}
}

void midOrder(Tree* root)
{
	stack<Tree*> q;
	while(root!=NULL||!q.empty())
	{
		if(root!=NULL){

			q.push(root);
			root=root->left;
		}else{
			root=q.top()->right;
			cout<<q.top()->val;
			q.pop();
		}
	}
}



void postorder(Tree *root)//可以用存pre指针,就不需要标记了
{
	stack<Tree*> q;
	q.push(root);
	while(!q.empty()){
		Tree *cur=q.top();
		if(flag[cur]==1||(cur->left==NULL&&cur->right==NULL)){
			printf("%d\n",cur->val);
			q.pop();
		}else{
			if(cur->right) q.push(cur->right);
			if(cur->left) q.push(cur->left);
			flag[cur]=1;
		}
	}
}



int main()
{
	Tree *a[20];
	a[7]=new Tree(7,0,0);
	a[6]=new Tree(6,0,a[7]);
	a[5]=new Tree(5,a[6],0);
	a[4]=new Tree(4,0,0);
	a[3]=new Tree(3,0,0);
	a[2]=new Tree(2,a[3],a[4]);
	a[1]=new Tree(1,a[2],a[5]);

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值