//建立 先中后序递归 非递归 层次遍历
#include <iostream>
#include<stack>
#include<stdio.h>
#include<stdlib.h>
#include<queue>
using namespace std;
typedef struct Node
{
char data;
struct Node* lchild, * rchild;
}BiTNode,*Bitree;
void CreateBiTree(Bitree* T)
{//创建二叉树
char ch;
ch = getchar();
if (ch == '#') {
*T = NULL;
return;
}
else {
*T = (Bitree)malloc(sizeof(BiTNode));
(*T)->data = ch;
CreateBiTree(&((*T)->lchild));
CreateBiTree(&((*T)->rchild));
}
}
//先中后序的递归遍历
void PreOrder(Bitree T)
{
if (T) {
cout << T->data;
PreOrder(T->lchild);
PreOrder(T->rchild);
}
else cout << "#";
}
void Inorder(Bitree T)
{
if (T) {
Inorder(T->lchild);
cout << T->data;
Inorder(T->rchild);
}
else cout << "#";
}
void Posorder(Bitree T)
{
if (T) {
Posorder(T->lchild);
Posorder(T->rchild);
cout << T->data;
}
else cout << "#";
}
//先中后序非递归遍历
Bitree p = nullptr;
stack<BiTNode*>s;//建栈
void FPreorder(Bitree T)
{
if (T == nullptr)
{return;}
else
{p = T;}//p为查找指针
do
{
while (p != NULL)
{
cout << p->data;
if (p->rchild != NULL)
{
s.push(p->rchild);//使p的右孩子入栈
}
else { s.push(NULL); }//没有右孩子就入栈空
p = p->lchild;
}cout << "#";p = s.top();s.pop();//如果上个结点的右孩子也为空就会跳出这层while 所以输出#并指向栈顶
} while ((!s.empty())|| (p != NULL));
cout << "#";//因为最后必为空才会出循环 但并没有输出最后一个右孩子 所以输出#
}
void FInorder(Bitree T)
{
if (T == nullptr)
{return;}
else
{ p = T;}
do
{
while (p != NULL)
{
s.push(p);
p = p->lchild;
}cout << "#";
if (!s.empty())
{
p = s.top();
s.pop();
cout << p->data;
p = p->rchild;
}
} while ((!s.empty())|| (p!= NULL));
cout << "#";
}
void FPosorder(Bitree T)
{
bool flag = true;
if (T == nullptr)
{return;}
else
{p = T;}
do
{
while (p != NULL)
{
s.push(p);p = p->lchild;
}cout << "#";
while(!s.empty()&&(p==NULL))
{
p = s.top();s.pop();
if (flag == true)
{
s.push(p);
p = p->rchild;
if (p == NULL)
{
s.push(NULL);
flag = false;
}
}
else if(p==NULL)
{
cout << "#";
p=s.top(); s.pop();
cout << p->data;
if(p==s.top()->rchild)
{p= s.top(); s.pop();
cout << p->data;
p = NULL;
flag = true;
}else
{p = NULL;flag = true;}
}
}
} while ((!s.empty()) || (p != NULL));
}
//层次遍历
void Levelorder(Bitree T)
{
queue<Bitree>queue;//建队列
if (T == nullptr) { return; }
p = T;
queue.push(p);//头节点入队
while (!queue.empty())
{
p = queue.front();
queue.pop();
cout << p->data;
if(p->lchild != nullptr)
{queue.push(p->lchild);}
if (p->rchild != nullptr)
{queue.push(p->rchild);}
}
}
int main()
{
Bitree T ;
cout << "创建一颗树,按先序输入,其中A-Z字符代表树的数据,用“#”表示空树:" << endl;
CreateBiTree(&T);
cout << "先序递归遍历:" << endl;
PreOrder(T);
cout << endl;
cout << "中序递归遍历:" << endl;
Inorder(T);
cout << endl;
cout << "后序递归遍历:" << endl;
Posorder(T);
cout << endl;
cout << "先序非递归遍历:" << endl;
FPreorder(T);
cout << endl;
cout << "中序非递归遍历:" << endl;
FInorder(T);
cout << endl;
cout << "后序非递归遍历:" << endl;
//FPosorder(T);
cout << endl;
cout << "层次遍历:" << endl;
Levelorder(T);
cout << endl;
return 0;
}
二叉树的先中后序的递归非递归遍历以及层次遍历(C++)
最新推荐文章于 2022-07-11 18:56:10 发布