非递归后序遍历二叉树

非递归后序遍历二叉树:

#include <iostream>
using namespace std;
/*
*writer:yaojinhui
*/
#define MAXSIZE 100
typedef struct BiTNode {
	char data;
	int isSecond;  // 增加标志位,初始值赋为0
	struct BiTNode *lchild,*rchild;
} BiTNode,*BiTree;
typedef struct 
{
	BiTree *base,*top;
	int stacksize;
}SqStack;
BiTree e;
int InitStack(SqStack &S)
{
	S.top=S.base=new BiTree[MAXSIZE];
	S.stacksize=MAXSIZE;
	return 1;
}
int Push(SqStack &S,BiTree e)
{
	if(S.top-S.base==S.stacksize)
		return 0;
	*S.top++=e;
	return 1;
}
int Pop(SqStack &S,BiTree &e)
{
	if(S.top==S.base)
		return 0;
	e=*--S.top;
	return 1;
}
int StackEmpty(SqStack S)
{
	if(S.top==S.base)
		return 1;
	else
		return 0;
}


void createBiTree(BiTree &T)
{
	char ch;
	cin>>ch;
	if(ch=='#')
		T=NULL;
	else
	{
		T=new BiTNode;
		T->data=ch;
		createBiTree(T->lchild);
		createBiTree(T->rchild);
	}
}

// 后序遍历1
// 后序遍历2
void printTreeLast(BiTree T)
{
	BiTree tmp = T;
	SqStack S;
	InitStack(S);
	SqStack S2;
	InitStack(S2);
	
	while(tmp) {
		Push(S2, tmp); // 打印改为压栈,临时保存起来
		Push(S, tmp);
		tmp = tmp->rchild;
	}
	
	while(!StackEmpty(S)) {
		Pop(S,e);
		tmp = e;
		tmp = tmp->lchild;
		while (tmp) {
			Push(S2, tmp);
			Push(S, tmp);
			tmp = tmp->rchild;
		}
	}
	
	// 再依次打印栈中的节点
	while(!StackEmpty(S2)) {
		Pop(S2,e);
		BiTree tmp = e;
		cout<<tmp->data<<"  ";
	//	printf("%d\n", tmp->data);
	}
}
int main()
{
	SqStack S;
	BiTree T;
	createBiTree(T);
	printTreeLast(T);
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

折戟不必沉沙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值