非递归先序遍历二叉树

非递归先序遍历二叉树由于要用到回溯,因此需要保存已访问过的根节点的指针。可以用栈来保存已访问过的根节点的指针,用于回溯。

代码如下

#include <iostream>
#define OK 1;
#define ERROR -1;
typedef char VertexType;
using namespace std;
typedef struct BinNode{
	VertexType data;
	struct BinNode *lchild,*rchild;
}BinNode,*bin_tree,*SElemType;

typedef struct{
	SElemType *base,*top;
}SqStack;

void InitStack(SqStack &S){
	S.base=(SElemType *)malloc(sizeof(SElemType));
	if(!S.top)
		exit(0);
	S.top=S.base;
}

int StackEmpty(SqStack S){
	return (S.base==S.top)?1:0;
}

void Push(SqStack &S,SElemType e){
	*S.top++=e;
}

int Pop(SqStack &S,SElemType &p){
	if(S.top==S.base)
		return ERROR;
	p=*--S.top;
	return OK;
}

BinNode *CreateTree(bin_tree &T){
	VertexType ch;
	cin>>ch;
	if(!cin.eof()){
		if(ch=='#')
			T=NULL;
		else{
			T=(BinNode *)malloc(sizeof(BinNode));
			if(!T)
				exit(0);
			T->data=ch;
			T->lchild=CreateTree(T->lchild);
			T->rchild=CreateTree(T->rchild);
		}
	}
	return T;
}

void PreOrderTraverse(bin_tree T){
	SqStack S;
	SElemType p;
	InitStack(S);
	p=T;
	while(p||!StackEmpty(S)){
		if(p){
			cout<<p->data<<"  ";
			Push(S,p);
			p=p->lchild;
		}else{
			Pop(S,p);
			p=p->rchild;
		}
	}
}

void main(){
	bin_tree T;
	cout<<"请输入二叉树的节点值:";
	CreateTree(T);
	cout<<"二叉树的非递归先序遍历结果是:";
	PreOrderTraverse(T);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值