#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;
}
二叉树非递归遍历算法一直都是考察热点
程序代码如下: