以先序遍历递归算法建立二叉树(’0’代表NULL),然后进行后序、中序、先序非递归遍历输出,再以层序遍历方式输出,最后先序遍历输出叶子结点,后序遍历获取树的高度。
#include<stack>
#include<queue>
#include<algorithm>
using namespace std;
typedef char EType;
struct BiTreeNode
{
EType data;
struct BiTreeNode *LChild;
struct BiTreeNode *RChild;
};
typedef BiTreeNode* BiTree;
typedef struct SType
{
BiTree ptr;
bool status;//进栈标志
}SType;
void CreatBiTree(BiTree &BT);
void PostOrderNoRecursive(BiTree &BT);
void PreOrderNoRecursive(BiTree &BT);
void InOrderNoRecursive(BiTree &BT);
void LevelOrderTraverse(BiTree &BT);
void PreFindLeafs(BiTree &BT);
int PostOrderGetHeight(BiTree &BT);
int main()
{
BiTree BT = NULL;
CreatBiTree(BT);
printf("后序遍历二叉树非递归算法输出为:");
PostOrderNoRecursive(BT);printf("\n");
printf("中序遍历二叉树非递归算法输出为:");
InOrderNoRecursive(BT);printf("\n");
printf("先序遍历二叉树非递归算法输出为:");
PreOrderNoRecursive(BT);printf("\n");
printf("层序遍历二叉树非递归算法输出为:");
LevelOrderTraverse(BT);printf("\n");
PreFindLeafs(BT);printf("\n");
printf("%d\n",PostOrderGetHeight(BT));
return 0;
}
void CreatBiTree(BiTree &BT)
{
EType tem;
scanf("%c",&tem);
if('0' == tem)
{
BT = NULL;
}
else
{
BT = new BiTreeNode;
BT->data = tem;
CreatBiTree(BT->LChild);
CreatBiTree(BT->RChild);
}
}
void PreOrderNoRecursive(BiTree &BT)
{
stack<SType> S;
SType temp;
BiTree p = BT;
while(p||!S.empty()){
if(p){
//保证这是第一次访问
printf("%c\t",p->data);
temp.ptr = p;
S.push(temp);
p = p->LChild;
}
else{
temp = S.top();
S.pop();
p = temp.ptr;
p = p->RChild;
}
}
}
void InOrderNoRecursive(BiTree &BT)
{
stack<SType> S;
SType temp;
BiTree p = BT;
while(p||!S.empty()){
if(p){
temp.ptr = p;
S.push(temp);
p = p->LChild;
}
else{
temp = S.top();
S.pop();
p = temp.ptr;
printf("%c\t",p->data);
p = p->RChild;
}
}
}
void PostOrderNoRecursive(BiTree &BT)
{
stack<SType> S;
SType temp;
BiTree p = BT;
while(p || !S.empty())
{
if(p)//找最左子树
{
temp.status = false;//设置该节点是第一次进栈
temp.ptr = p;
S.push(temp);
p = p->LChild;
}
else
{
if(!S.empty())
{
temp = S.top();
S.pop();
p = temp.ptr;
if(temp.status)//若该节点是第二次退栈,就访问,并设置p=0继续退栈
{
printf("%c\t",p->data);
p = NULL;//不要忘了
}
else
{
temp.status = true;//设置该节点是第二次进栈,A0BCD0000
S.push(temp);
p = p->RChild;//遍历该节点的右子树
}
}
}
}
}
void LevelOrderTraverse(BiTree &BT)
{
queue<BiTree> Q;
BiTree p = BT;
Q.push(p);
while(!Q.empty()){
p = Q.front();
Q.pop();
printf("%c\t",p->data);
if(p->LChild!=NULL) Q.push(p->LChild);
if(p->RChild!=NULL) Q.push(p->RChild);
}
}
void PreFindLeafs(BiTree &BT)
{
BiTree p = BT;
if(p){
if(!p->LChild&&!p->RChild)
printf("%c\t",p->data);
if(p->LChild)
PreFindLeafs(p->LChild);
if(p->RChild)
PreFindLeafs(p->RChild);
}
}
int PostOrderGetHeight(BiTree &BT)
{
BiTree p = BT;
int HL,HR;//左右子树的高度
if(p!=NULL){
HL = PostOrderGetHeight(p->LChild);
HR = PostOrderGetHeight(p->RChild);
return max(HL,HR)+1;
}
else return 0;
}