#include <iostream>
#include <queue>
#include <stack>
using namespace std;
struct NODE
{
int data;
NODE* lchild;
NODE* rchild;
};
//递归前序遍历
void PreOrder(NODE* pRoot)
{
if(!pRoot)return;
cout<<pRoot->data<<" ";
PreOrder(pRoot->lchild);
PreOrder(pRoot->rchild);
}
//递归中序遍历
void InOrder(NODE* pRoot)
{
if(!pRoot)return;
InOrder(pRoot->lchild);
cout<<pRoot->data<<" ";
InOrder(pRoot->rchild);
}
//递归后序遍历
void PostOrder(NODE* pRoot)
{
if(!pRoot)return;
PostOrder(pRoot->lchild);
PostOrder(pRoot->rchild);
cout<<pRoot->data<<" ";
}
//非递归前序遍历
void FeiDiGuiDLR(NODE* pRoot)
{
if(!pRoot)return;
stack<NODE*> S;
NODE* pNode=pRoot;
while(pNode || !S.empty())
{
while(pNode)//遍历左子树
{
cout<<pNode->data<<" ";
S.push(pNode);
pNode=pNode->lchild;
}
if(!S.empty())//通过下一次循环中的内嵌while实现右子树遍历
{
pNode=S.top();
pNode=pNode->rchild;
S.pop();
}
}
}
//非递归中序遍历
void NonRecursiveInOrder(NODE* pRoot)
{
if(!pRoot)return;
stack<NODE*> S;
S.push(pRoot);
while(!S.empty())
{
NODE* pNode=S.top();
while(pNode)//向左走到尽头
{
pNode=pNode->lchild;
S.push(pNode);
}
S.pop();//空指针出栈
if(!S.empty())//必须判断,否则遍历完最后一个节点将陷入死循环
{
pNode=S.top();
cout<<pNode->data<<" ";
S.pop();
S.push(pNode->rchild);
}
}
}
//层次遍历
void LevelOrder(NODE* pRoot)
{
if(!pRoot)return;
queue<NODE*> Q;
Q.push(pRoot);
while(!Q.empty())
{
NODE* pNode=Q.front();
cout<<pNode->data<<" ";
if(pNode->lchild)Q.push(pNode->lchild);
if(pNode->rchild)Q.push(pNode->rchild);
Q.pop();
}
}
//将nodes中的节点之间建立父子关系
void Link(NODE* nodes,int parent,int left,int right)
{
if(!nodes)return;
if(left!=-1)nodes[parent].lchild=&nodes[left];
if(right!=-1)nodes[parent].rchild=&nodes[right];
}
int main()
{
NODE nodes[10];
for(int i=0;i<10;i++)
{
nodes[i].data=i+1;
nodes[i].lchild=NULL;
nodes[i].rchild=NULL;
}
Link(nodes,0,1,2);
Link(nodes,1,3,4);
Link(nodes,2,5,6);
Link(nodes,3,7,8);
Link(nodes,4,9,-1);
cout<<"PreOrderTraverse: ";
PreOrder(nodes);
cout<<endl;
cout<<"InOrderTraverse: ";
InOrder(nodes);
cout<<endl;
cout<<"PostOrderTraverse: ";
PostOrder(nodes);
cout<<endl;
cout<<"NonRecursiveInOrder: ";
NonRecursiveInOrder(nodes);
cout<<endl;
cout<<"LevelOrderTraverse: ";
LevelOrder(nodes);
cout<<endl;
return 0;
}
二叉树遍历(前序、中序、后序、非递归中序、层次)
最新推荐文章于 2022-08-22 15:37:08 发布