#include <iostream>
#include <stack>
//using stack;
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
};
Node* insert(Node*p, int n)
{
Node *f = p;
Node *r = p;
while (p != NULL)
{
f = p;
if (n < p->data)
p = p->left;
else if (n > p->data)
p = p->right;
else
return p;
}
p = new Node;
p->data = n;
p->left = NULL;
p->right = NULL;
if (f)
{
if (n < f->data)
f->left = p;
else
f->right = p;
return r;
}
return p;
}
Node* creat(Node *p, int *pi, int m, int n)
{
if(m > n)
return p;
int x = m+((n-m)>>1);
p = new Node;
p->data = pi[x];
p->left = NULL;
p->right = NULL;
p->left = creat(p->left, pi, m, x-1);
p->right = creat(p->right, pi, x+1, n);
return p;
}
void del(Node *p)
{
if (p==NULL)
return;
if (p->left != NULL)
del(p->left);
if (p->right != NULL)
del(p->right);
delete p;
p = NULL;
}
void preOrder0(Node *p)
{
if(p == NULL)
return;
cout<<p->data<<" ";
preOrder0(p->left);
preOrder0(p->right);
}
void inOrder0(Node *p)
{
if(p == NULL)
return;
inOrder0(p->left);
cout<<p->data<<" ";
inOrder0(p->right);
}
void postOrder0(Node *p)
{
if(p == NULL)
return;
postOrder0(p->left);
postOrder0(p->right);
cout<<p->data<<" ";
}
void preOrder(Node *p)
{
if (p == NULL)
return;
stack<Node*>st;
while(true)
{
for(;p != NULL; p = p->left)
{
cout<<p->data<<" ";
if (p->right != NULL)
st.push(p->right);
}
if (!st.empty())
{
p = st.top();
st.pop();
}else
{
break;
}
}
}
void inOrder(Node *p)
{
if (p == NULL)
return;
stack<Node*>st;
while(true)
{
for(;p != NULL; p = p->left)
{
st.push(p);
}
if (!st.empty())
{
p = st.top();
st.pop();
cout<<p->data<<" ";
p = p->right;
}else
{
break;
}
}
}
void postOrder(Node *p)
{
if (p == NULL)
return;
stack<Node*>st;
Node *last = NULL;
while(true)
{
for(; p!=NULL; p=p->left)
st.push(p);
while(true)
{
if (st.empty())
return;
p = st.top();
if (p->right != NULL && p->right != last)
{
p = p->right;
break;
}
else
{
cout<<p->data<<" ";
last = p;
st.pop();
}
}
}//
}
int main()
{
int a[] = {1,2,3,4,5,6,7,8};
Node * p=NULL;
p = insert(p,6);
p = insert(p,3);
p = insert(p,8);
p = insert(p,2);
p = insert(p,1);
p = insert(p,4);
p = insert(p,5);
p = insert(p,9);
p = insert(p,7);
cout<<"前序遍历"<<endl;
cout<<"迭代: ";
preOrder(p);
cout<<endl;
cout<<"递归: ";
preOrder0(p);
cout<<endl;
cout<<"中序遍历"<<endl;
cout<<"迭代: ";
inOrder(p);
cout<<endl;
cout<<"递归: ";
inOrder0(p);
cout<<endl;
cout<<"后序遍历"<<endl;
cout<<"迭代: ";
postOrder(p);
cout<<endl;
cout<<"递归: ";
postOrder0(p);
cout<<endl;
del(p);
return 0;
}