#include <iostream>
#include <stack>
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct BTNode
{
BiTNode * btNode;
bool visit;
}*pBTNode;
void CreateBiTree(BiTree* T)
{
char input;
cin>>input;
if(input == '#')
*T = NULL;
else
{
*T = new BiTNode;
(*T)->data = input;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
void PreOrderTraverse(BiTree T)
{
stack<BiTree> s;
BiTree p = T;
while(p!=NULL || !s.empty())
{
while(p != NULL)
{
cout<<p->data;
s.push(p);
p = p->lchild;
}
if(!s.empty())
{
p = s.top();
s.pop();
p = p->rchild;
}
}
}
void InOrderTraverse(BiTree T)
{
stack<BiTree> s;
BiTree p = T;
while(p!=NULL || !s.empty())
{
while(p!=NULL)
{
s.push(p);
p = p->lchild;
}
if(!s.empty())
{
p = s.top();
s.pop();
cout<<p->data;
p = p->rchild;
}
}
}
void LastOrderTraverse(BiTree T)
{
stack<pBTNode> s;
BiTree p =T;
pBTNode tmp;
while(p!=NULL || !s.empty())
{
while(p!=NULL)
{
pBTNode btn = new BTNode;
btn->btNode = p;
btn->visit = true;
s.push(btn);
p = p->lchild;
}
if(!s.empty())
{
tmp = s.top();
s.pop();
if(tmp->visit == true)
{
tmp->visit = false;
s.push(tmp);
p = tmp->btNode->rchild;
}
else
{
cout<<tmp->btNode->data;
p = NULL;
}
}
}
}
int main()
{
BiTree myBT;
CreateBiTree(&myBT);
cout<<"\n====================Pre Order Traverse======================\n";
PreOrderTraverse(myBT);
cout<<"\n====================In Order Traverse======================\n";
InOrderTraverse(myBT);
cout<<"\n====================Lase Order Traverse======================\n";
LastOrderTraverse(myBT);
return 0;
}
層序遍歷:
層序遍歷需要藉助隊列來實現非遞歸。
void LeverlOrder(BiTree T)
{
Queue Q;
InitQueue Q;
BiTree P;
EnQueue(Q,T); //根節點入隊列
while(!Q.isEmpty()) //隊列不爲空,則循環
{
DeQueue(Q,p); //隊頭元素出隊
Visit(p); //訪問當前p所指向的節點
if(p->lchild != NULL) // 左子樹不爲空,則左子樹入隊
EnQueue(Q,p->lchild);
if(P->rchild != NULL) // 右子樹不爲空,則右子樹入隊
EnQueue(Q,p->rchild);
}
}
二叉樹深度遍歷:
int TreeDepth(BinaryTreeNode *pTreeNode)
{
if(!pTreeNode)
return 0;
int nLeft = TreeDepth(pTreeNode->m_pLeft);
int nRight = TreeDepth(pTreeNode->m_pRight);
return (nLeft>nRight)?(nLeft + 1) : (nRight + 1);
}