二叉树非递归遍历算法

#include 
#include 

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<data<<" ";
		
		inorder(root->right);
	}
	
}

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


void postorder(bintree *root){
	if(root!=NULL)
	{
		
		postorder(root->left);
		postorder(root->right);
		cout<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<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<data<<" ";
		s[top++]=root;
		root=root->left;
	}
	while(top!=0||Ptr!=NULL){
		Ptr=s[--top];
		Ptr=Ptr->right;
		while(Ptr!=NULL){
			cout<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<data<<" ";
			top--;
		}
	}
}












int main()
{
	bintree *root=NULL;
	root=creatTree(root);
	cout<

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

程序代码如下:


你可能感兴趣的:(数据结构)