#include <iostream>
#include <stack>
#include <list>
using namespace std;
typedef int ElemType;
typedef struct treeT
{
ElemType key;
struct treeT* left;
struct treeT* right;
}treeT, *pTreeT;
class BITree{
public:
pTreeT Insert(ElemType target, pTreeT* ppTree);
void PreOrder(pTreeT root);
void lev_Order(pTreeT);
void InOrderNoRec(pTreeT root);
void PreOrderNoRec(pTreeT root);
void PosOrderNoRec(pTreeT root);
};
pTreeT BITree::Insert(ElemType target, pTreeT* ppTree)
{
pTreeT Node;
Node = *ppTree;
if (NULL == Node)
{
Node=(pTreeT)malloc(sizeof(treeT));
Node->key = target;
Node->left = NULL;
Node->right = NULL;
*ppTree=Node;
return *ppTree ;
}
if (Node->key == target) //不允许出现相同的元素
{
return NULL;
}
else if (Node->key > target) //向左
{
return Insert(target, &Node->left);
}
else
{
return Insert(target, &Node->right);
}
}
void BITree::PreOrder(pTreeT root)
{
if(root!=NULL)
{
cout<<root->key<<",";
PreOrder(root->left);
PreOrder(root->right);
}
}
void BITree::lev_Order(pTreeT root) // 层次遍历
{
list<pTreeT> list1;
pTreeT p;
list1.push_back(root);
while(!list1.empty())
{
p=(pTreeT)list1.front();
list1.pop_front();
cout<<p->key<<",";
if(p->left!=NULL)
list1.push_back(p->left);
if(p->right!=NULL)
list1.push_back(p->right);
}
}
void BITree::InOrderNoRec(pTreeT root)
{
stack<pTreeT > s;
while ((NULL != root) || !s.empty())
{
if (NULL != root)
{
s.push(root);
root = root->left;
}
else
{
root = s.top();
cout<<root->key<<",";
s.pop();
root = root->right;
}
}
}
void BITree::PreOrderNoRec(pTreeT root)
{
stack<pTreeT > s;
while ((NULL != root) || !s.empty())
{
if (NULL != root)
{
cout<<root->key<<",";
s.push(root);
root = root->left;
}
else
{
root = s.top();
s.pop();
root = root->right;
}
}
}
void BITree::PosOrderNoRec(pTreeT root)
{
stack<pTreeT> st;
pTreeT p = root;
pTreeT pre = NULL;//pre表示最近一次访问的结点
while(p || st.size()!=0)
{
//沿着左孩子方向走到最左下 。
while(p)
{
st.push(p);
p = p->left;
}
//get the top element of the stack
p = st.top();
//如果p没有右孩子或者其右孩子刚刚被访问过
if(p->right == NULL || p->right == pre)
{
//visit this element and then pop it
cout<< p->key<<",";
st.pop();
pre = p;
p = NULL;
}
else
{
p = p->right;
}
}
}
// 测试程序
#include "Tree.h"
void main()
{
BITree bitree;
pTreeT root = NULL;
bitree.Insert(10, &root);
bitree.Insert(8, &root);
bitree.Insert(7, &root);
bitree.Insert(9, &root);
bitree.Insert(12, &root);
bitree.Insert(11, &root);
bitree.Insert(13, &root);
//递归先序遍历
cout<<"递归先序遍历"<<endl;
bitree.PreOrder(root);
//层次遍历(队列实现)
cout<<endl<<"层次遍历(队列实现)"<<endl;
bitree.lev_Order(root);
//非递归先序遍历
cout<<endl<<"非递归先序遍历"<<endl;
bitree.PreOrderNoRec(root);
//非递归中序遍历
cout<<endl<<"非递归中序遍历"<<endl;
bitree.InOrderNoRec(root);
//非递归后序遍历
cout<<endl<<"非递归后序遍历"<<endl;
bitree.PosOrderNoRec(root);
}