#include <iostream>
#include <string>
#define MAX_SIZE 50
#define INCRE_SIZE 10
#define NULL 0
using namespace std;
class BiNode
{
//member data variant
public:
char data;
BiNode *lchild;
BiNode *rchild;
//member function
public:
BiNode();
};
BiNode::BiNode()
{
data='#';
lchild=NULL;
rchild=NULL;
}
typedef BiNode *BiTree;
class Stack
{
//member data variant
public:
BiTree *elem;
int top;
int base;
int stack_size;
int length;
//member function
public:
Stack();
void push(BiTree &ele);
void pop(BiTree &ele);
bool isEmpty(){ return !length; }
bool getTop(BiTree &ele);
};
Stack::Stack()
{
elem=new BiTree[MAX_SIZE];
top=0;
base=0;
stack_size=50;
length=0;
}
void Stack::push(BiTree &ele)
{
//if(size>=stack_size)
//process
elem[top++]=ele;
length++;
}
void Stack::pop(BiTree &ele)
{
ele=elem[--top];
length--;
}
bool Stack::getTop(BiTree &ele)
{
if(length==0)
return 0;
ele=elem[top-1];
return 1;
}
void createBitree(BiTree &root)
{
//preorder
char ch;
cin>>ch;
if(ch=='#')
{
root=NULL;
return ;
}
else
{
root=new BiNode;
root->data=ch;
createBitree(root->lchild);
createBitree(root->rchild);
}
}
void preprint(BiTree &root)
{
if(root)
{
cout<<root->data<<" ";
preprint(root->lchild);
preprint(root->rchild);
}
else
cout<<"NULL"<<" ";
}
void inprint(BiTree &root)
{
if(root)
{
inprint(root->lchild);
cout<<root->data<<" ";
inprint(root->rchild);
}
else
cout<<"NULL"<<" ";
}
//二叉树的中序非递归算法
void InOrder(BiTree &root)
{
Stack s;
s.push(root);
BiTree p;
while(!s.isEmpty())
{
while(s.getTop(p) && p)
s.push(p->lchild);
s.pop(p);
if(!s.isEmpty())
{
s.pop(p);
cout<<p->data<<" ";
s.push(p->rchild);
}
}
}
//二叉树的先序非递归算法
void PreOrder(BiTree &root)
{
Stack s;
s.push(root);
BiTree p;
while(!s.isEmpty())
{
while(s.getTop(p)&&p)
{
cout<<p->data<<" ";
s.push(p->lchild);
}
s.pop(p);
if(!s.isEmpty())
{
s.pop(p);
s.push(p->rchild);
}
}
}
int main()
{
/*
BiTree bt1=new BiNode;
BiTree bt2=new BiNode;
Stack sta;
bt1->data='f';
sta.push(bt1);
sta.pop(bt2);
cout<<bt2->data;*/
BiTree t=NULL;
preprint(t);
cout<<"Please create the Bitree:";
createBitree(t);
preprint(t);
cout<<'/n';
inprint(t);
cout<<'/n';
PreOrder(t);
cout<<'/n';
InOrder(t);
}