看代码一目了然。
C++代码:
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
//二叉树节点
typedef struct BitNode{
char data;
BitNode *lchild;
BitNode *rchild;
}BitNode, *BiTree;
//按先序次序建立二叉树,注意传参时的引用
void creatBiTree(BiTree &T)
{
char tmp;
cin>>tmp;
if (tmp == '#')
{
T = NULL;
return;
}
else
{
T = (BiTree)malloc(sizeof(BitNode));
T->data = tmp;
creatBiTree(T->lchild);
creatBiTree(T->rchild);
}
}
//递归实现先序遍历
void preOrder(BiTree T)
{
if (T)
{
cout<<T->data;
preOrder(T->lchild);
preOrder(T->rchild);
}
}
//递归实现中序遍历
void inOrder(BiTree T)
{
if (T)
{
inOrder(T->lchild);
cout<<T->data;
inOrder(T->rchild);
}
}
//递归实现后序遍历
void postOrder(BiTree T)
{
if (T)
{
postOrder(T->lchild);
postOrder(T->rchild);
cout<<T->data;
}
}
//非递归实现先序遍历
// 思路:访问完T之后将T入栈,然后访问T的左子树,访问完T的左子树后将T出栈,然后访问T的右子树
void preOrder2(BiTree T)
{
stack<BiTree> st;
while (T || !st.empty())
{
if (T)
{
cout<<T->data;
st.push(T);
T = T->lchild;
}
else
{
BiTree tmp = st.top();
st.pop();
T = tmp->rchild;
}
}
}
//非递归实现中序遍历
// 思路:将T入栈,然后访问T的左子树,访问完T的左子树后将T出栈访问T,然后访问T的右子树
void inOrder2(BiTree T)
{
stack<BiTree> st;
while (T || !st.empty())
{
if (T)
{
st.push(T);
T = T->lchild;
}
else
{
BiTree tmp = st.top();
cout<<tmp->data;
st.pop();
T = tmp->rchild;
}
}
}
//非递归实现后序遍历
//思路:后序遍历要先遍历完左子树后再遍历右子树,然后再访问T。需要判断根节点的左右子树是否遍历过
typedef struct BitNodePost{
BiTree tree;
char tag;
}BitNodePost;
void postOrder2(BiTree T)
{
stack<BitNodePost> st;
while (T || !st.empty())
{
//遍历左子树
while (T)
{
BitNodePost bp;
bp.tree = T;
bp.tag = 'L';
st.push(bp);
T = T->lchild;
}
//当左右子树访问之后
//注意该层while循环不能放在下面if语句之后,因为下面的语句会将st.top().tag 赋值为'R',使该处判断条件为真
while (!st.empty() && st.top().tag == 'R')
{
cout<<st.top().tree->data;
st.pop();
}
//访问右子树
if (!st.empty() && st.top().tag == 'L')
{
st.top().tag = 'R';
T = st.top().tree->rchild;
}
}
}
//层次遍历
void levelOrder(BiTree T)
{
queue<BiTree> q;
if (T == NULL) return;
q.push(T);
while (!q.empty())
{
BiTree bt = q.front();
cout<<bt->data;
if (bt->lchild) q.push(bt->lchild);
if (bt->rchild) q.push(bt->rchild);
q.pop();
}
}
//销毁树
void destoryBiTree(BiTree T)
{
if (T)
{
destoryBiTree(T->lchild);
destoryBiTree(T->rchild);
free(T);
T = NULL;
}
}
int main()
{
BiTree tree = NULL;
cout<<"请输入二叉树的先序序列:";
creatBiTree(tree);
cout<<endl;
cout<<"二叉树的递归先序遍历结果为:";
preOrder(tree);
cout<<endl;
cout<<"二叉树的非递归先序遍历结果为:";
preOrder2(tree);
cout<<endl<<endl;
cout<<"二叉树的递归中序遍历结果为:";
inOrder(tree);
cout<<endl;
cout<<"二叉树的非递归中序遍历结果为:";
inOrder2(tree);
cout<<endl<<endl;
cout<<"二叉树的递归后序遍历结果为:";
postOrder(tree);
cout<<endl;
cout<<"二叉树的非递归后序遍历结果为:";
postOrder2(tree);
cout<<endl<<endl;
cout<<"二叉树的层次遍历结果为:";
levelOrder(tree);
cout<<endl;
destoryBiTree(tree);
return 0;
}
//abd#e##fg###c##
测试用例:
运行结果: