#include "stdafx.h"
#include<iostream>
#include<stack>
#include<queue>
using namespace std
;
typedef struct BiTNode
{
char data
;
struct BiTNode
*lchild
,*rchild
;
}BiTNode
,*BiTree
;
int CreateBiTree(BiTree
&T
){
char data
;
scanf("%c",&data
);
if(data
== '#'){
T
= NULL;
}
else{
T
= (BiTree
)malloc(sizeof(BiTNode
));
T
->data
= data
;
CreateBiTree(T
->lchild
);
CreateBiTree(T
->rchild
);
}
return 0;
}
void Visit(BiTree T
){
if(T
->data
!= '#'){
printf("%c ",T
->data
);
}
}
void PreOrder(BiTree T
){
if(T
!= NULL){
Visit(T
);
PreOrder(T
->lchild
);
PreOrder(T
->rchild
);
}
}
void InOrder(BiTree T
){
if(T
!= NULL){
InOrder(T
->lchild
);
Visit(T
);
InOrder(T
->rchild
);
}
}
void PostOrder(BiTree T
){
if(T
!= NULL){
PostOrder(T
->lchild
);
PostOrder(T
->rchild
);
Visit(T
);
}
}
void PreOrder2(BiTree T
){
stack
<BiTree
> stack
;
BiTree p
= T
;
while(p
|| !stack
.empty()){
if(p
!= NULL){
stack
.push(p
);
printf("%c ",p
->data
);
p
= p
->lchild
;
}
else{
p
= stack
.top();
stack
.pop();
p
= p
->rchild
;
}
}
}
void InOrder2(BiTree T
){
stack
<BiTree
> stack
;
BiTree p
= T
;
while(p
|| !stack
.empty()){
if(p
!= NULL){
stack
.push(p
);
p
= p
->lchild
;
}
else{
p
= stack
.top();
printf("%c ",p
->data
);
stack
.pop();
p
= p
->rchild
;
}
}
}
typedef struct BiTNodePost
{
BiTree biTree
;
char tag
;
}BiTNodePost
,*BiTreePost
;
void PostOrder2(BiTree T
){
stack
<BiTreePost
> stack
;
BiTree p
= T
;
BiTreePost BT
;
while(p
!= NULL || !stack
.empty()){
while(p
!= NULL){
BT
= (BiTreePost
)malloc(sizeof(BiTNodePost
));
BT
->biTree
= p
;
BT
->tag
= 'L';
stack
.push(BT
);
p
= p
->lchild
;
}
while(!stack
.empty() && (stack
.top())->tag
== 'R'){
BT
= stack
.top();
stack
.pop();
BT
->biTree
;
printf("%c ",BT
->biTree
->data
);
}
if(!stack
.empty()){
BT
= stack
.top();
BT
->tag
= 'R';
p
= BT
->biTree
;
p
= p
->rchild
;
}
}
}
void LevelOrder(BiTree T
){
BiTree p
= T
;
queue
<BiTree
> queue
;
queue
.push(p
);
while(!queue
.empty()){
p
= queue
.front();
printf("%c ",p
->data
);
queue
.pop();
if(p
->lchild
!= NULL){
queue
.push(p
->lchild
);
}
if(p
->rchild
!= NULL){
queue
.push(p
->rchild
);
}
}
}
int main()
{
BiTree T
;
CreateBiTree(T
);
printf("先序遍历:\n");
PreOrder(T
);
printf("\n");
printf("先序遍历(非递归):\n");
PreOrder2(T
);
printf("\n");
printf("中序遍历:\n");
InOrder(T
);
printf("\n");
printf("中序遍历(非递归):\n");
InOrder2(T
);
printf("\n");
printf("后序遍历:\n");
PostOrder(T
);
printf("\n");
printf("后序遍历(非递归):\n");
PostOrder2(T
);
printf("\n");
printf("层次遍历:\n");
LevelOrder(T
);
printf("\n");
system("pause");
return 0;
}
参考链接:https://www.bilibili.com/video/av23885544?from=search&seid=6629169072442500924
转载请注明原文地址: https://yun.8miu.com/read-139964.html