#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef struct BinaryTree
{
char val;
struct BinaryTree *left;
struct BinaryTree *right;
}BinaryTree,*BitTree;
//******递归建立二叉树*****//
//先建立根节点,再建立左子树,最后建立右子树
/***********
测试用例:
a
b c
# d # e
f # # #
# #
输入:ab#df###c#e##
***************/
int create_tree(BitTree &T)
{
char val = getchar();
if(val == '#')
T = NULL;
else
{
T = new BinaryTree;
T -> val = val;
create_tree(T->left);
create_tree(T->right);
}
return 0;
}
//二叉树先序非递归遍历
int Preorder(BitTree T)
{
stack<BitTree> sta;
BitTree p = T;
while(p || !sta.empty())
{
if(p)
{
//输出根节点,根节点入栈,遍历左子树
cout<<p->val<<" ";
sta.push(p);
p = p->left;
}
else
{
//记录根节点,然后根节点出栈,遍历右子树
p = sta.top();
sta.pop();
p = p->right;
}
}
return 0;
}
//二叉树中序非递归遍历
int Midorder(BitTree T)
{
stack<BitTree> sta;
BitTree p = T;
while(p || !sta.empty())
{
if(p)
{
//此时不输出根节点,根节点入栈,遍历左子树
sta.push(p);
p = p->left;
}
else //当走到最左端时,弹出栈顶,打印输出该节点,转向右节点
{
p = sta.top();
sta.pop();
cout<<p->val<<" ";
p = p->right;
}
}
return 0;
}
//二叉树后序非递归遍历
int Postorder(BitTree T)
{
stack<BitTree > sta;
//bool flag = false;
BitTree pLastvisit,p; //pLastvisit标记上次访问的节点
pLastvisit = NULL; //p标记当前访问节点
p = T;
while(p) //寻找整棵树最左边的节点
{
sta.push(p);
p=p->left;
}
while(!sta.empty())
{
p = sta.top();
sta.pop();
//根节点被访问的前提是:无右子树或者右子树被访问过
if(p->right==NULL|| p->right==pLastvisit)
{
cout<<p->val<<" ";
//修改上次被访问的节点
pLastvisit = p;
}
else //否则根节点现在不能访问
{
sta.push(p);//根节点需要再次入栈
p = p->right;
while(p) //寻找右子树中最左边的节点
{
sta.push(p);
p = p->left;
}
}
}
return 0;
}
//*****按层遍历(未分层打印)*****//
int layerorder(BitTree T)
{
queue<BitTree> q;
BitTree p = NULL;
if(T)
q.push(T); //根节点入队列
while(!q.empty())
{
p = q.front();
q.pop();
cout<<p->val<<" "; //打印根节点,左右子节点非空,即入队列
if(p->left)
q.push(p->left);
if(p->right)
q.push(p->right);
}
cout<<endl;
return 0;
}
int main()
{
BitTree T;
create_tree(T);
cout<<endl<<"非递归先序遍历:"<<endl;
Preorder(T);
cout<<endl<<"非递归中序遍历:"<<endl;
Midorder(T);
cout<<endl<<"非递归后序遍历:"<<endl;
Postorder(T);
cout<<endl<<"层次遍历:"<<endl;
layerorder(T);
return 0;
}
程序运行结果: