c++ 二叉查找树 非递归(先序、中序、后序)遍历
关键词: c++ 二叉查找树 非递归(先序、中序、后序)遍历
#include <iostream.h>
#include <malloc.h>
#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* pp Tree);
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* pp Tree)
{
pTreeT Node;
Node = * pp Tree;
if (NULL == Node)
{
Node=(pTreeT)malloc(sizeof(treeT));
Node->key = target;
Node->left = NULL;
Node->right = NULL;
* pp Tree=Node;
return * pp Tree ;
}
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 <iostream.h>
#include "Tree.h"
#include <malloc.h>
#include <assert.h>
void main()
{
BITree bitree;
//int i;
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);
}