二叉树非递归遍历算法

#include <iostream>
#include <malloc.h>

using namespace std;
struct bintree{
	int flag;
	int data;
	bintree *left;
	bintree *right;
};

bintree* creatTree(bintree *root){
	int testdata;
	cout<<"please input the data:";
	cin>>testdata;
	if(testdata==0) return NULL;
	root=(bintree *)malloc(sizeof(bintree));
	if(root==NULL) cout<<"failed to ask for space\n";
	{root->data=testdata;
	root->flag=0;
	}
	root->left=creatTree(root->left);
	root->right=creatTree(root->right);
	return root;
	
}
void inorder(bintree *root){
	if(root!=NULL)
	{
		
		inorder(root->left);
		cout<<root->data<<" ";
		
		inorder(root->right);
	}
	
}

void preorder(bintree *root){
	if(root!=NULL)
	{
		cout<<root->data<<" ";
		preorder(root->left);
		preorder(root->right);
	}
	
}


void postorder(bintree *root){
	if(root!=NULL)
	{
		
		postorder(root->left);
		postorder(root->right);
		cout<<root->data<<" ";
	}
	
}


void  noInverseInOrder(bintree *root){
	
	bintree *s[100];
	int top=0;
	bintree *Ptr=root;
	if(root==NULL)
		return;
	while(Ptr!=NULL){
		s[top++]=Ptr;
		Ptr=Ptr->left;
	}
	while(top!=0||Ptr!=NULL){
		Ptr=s[--top];
		cout<<Ptr->data<<" ";
		Ptr=Ptr->right;
		while(Ptr!=NULL){
			s[top++]=Ptr;
			Ptr=Ptr->left;
		}
	}
	
	
}

void noInversePreOrder(bintree *root){
	bintree *s[100];
	int top=0;
	bintree *Ptr=root;
	while(root!=NULL){
		cout<<root->data<<" ";
		s[top++]=root;
		root=root->left;
	}
	while(top!=0||Ptr!=NULL){
		Ptr=s[--top];
		Ptr=Ptr->right;
		while(Ptr!=NULL){
			cout<<Ptr->data<<" ";
			s[top++]=Ptr;
			Ptr=Ptr->left;
		}
	}
	
}


void noInversepostOrder(bintree *root){
	bintree *s[100];
	int top=0;
	bintree *Ptr=root;
	s[top++]=root;
	while(top!=0||Ptr!=NULL){
		if(top!=0)
			Ptr=s[top-1];
		if(Ptr->flag==0){
			Ptr->flag++;
			if(Ptr->left!=NULL)
				s[top++]=Ptr->left;
		}
		else if(Ptr->flag==1){
			Ptr->flag++;
			if(Ptr->right!=NULL)
				s[top++]=Ptr->right;
		}
		else if(Ptr->flag==2){
			cout<<Ptr->data<<" ";
			top--;
		}
	}
}












int main()
{
	bintree *root=NULL;
	root=creatTree(root);
	cout<<endl;
	preorder(root);
	cout<<endl;
	noInversePreOrder(root);
	cout<<endl;
	inorder(root);
	cout<<endl;
	noInverseInOrder(root);
	cout<<endl;
	postorder(root);
	cout<<endl;
	noInversepostOrder(root);
	
	
	cout << "Hello world!" << endl;
	return 0;
}

二叉树非递归遍历算法一直都是考察热点

程序代码如下:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值