二叉樹的前序、中序、後序的遞迴與非遞迴遍歷演算法實現
阿新 • • 發佈:2019-02-20
看程式碼一目瞭然。
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##
測試用例:
執行結果: