遍历
是指按照某条搜索路径访问树中每个结点,并且每个结点都被访问一次,且只访问一次。
遍历分为
前序遍历:根左右;
中序遍历:左根右;
后序遍历:左右根。
代码
#include <iostream>
#include <stdlib.h>
using namespace std;
#define MaxSize 100
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top;
} Stack;
Stack s;
typedef struct LinkNode{//队列
ElemType data;
struct LinkNode *next;
}LinkNode;
typedef struct {
LinkNode *front,*rear;
}LinkQueue;
LinkQueue q;
typedef struct BiTNode {
ElemType c;
struct BiTNode *lchild;
struct BiTNode *rchild;
} BiTNode, *BiTree;
typedef struct tag {
struct tag *pnext;
BiTree p;
} tag_t, *ptag_t;
void InitStack(Stack &s) {//初始化
s.top = -1;//because
}
bool Push(Stack &s, ElemType x) { //入栈
if (s.top == MaxSize - 1)return false; //健壮性
s.data[++s.top] = x;
return true;
}
bool pop(Stack &s, ElemType &x) {//出栈
if (s.top == -1) {
return false;
}
x = s.data[s.top--];
return true;
}
void InitQueue(LinkQueue &Q){
Q.front=Q.rear=(LinkNode*)malloc(sizeof(LinkNode));
Q.front->next=NULL;
}
void EnQueue(LinkQueue &Q,ElemType x){//进队
LinkNode *pnew=(LinkNode*)malloc(sizeof(LinkNode));
pnew->data=x;
pnew->next=NULL;
Q.rear->next=pnew;
Q.rear=pnew;
}
bool DeQueue(LinkQueue &Q,ElemType &x){
if(Q.rear==Q.front) return false;
LinkNode*q=Q.front->next;
x=q->data;
Q.front->next=q->next;
if(Q.rear==q) Q.rear=Q.front;
free(q);
return true;
}
void Empty(BiTree p) {return 0;}
void LevelOrder(BiTree t){
InitQueue(q);
BiTree p;
EnQueue(q,t->c);
while(!Empty(q)){//判断q是否为空(其中Empty这个函数不存在)
DeQueue(q,p->c);
cout<<p->c;
if(p->lchild!=NULL) EnQueue(q,p->lchild->c);
if(p->rchild!=NULL) EnQueue(q,p->rchild->c);
}
}
/*void PreOrder(BiTree p) { //前序遍历(不用栈)
if (p != NULL) {
cout << p->c;
PreOrder(p->lchild);
PreOrder(p->rchild);
}
}*/
void InOrder(BiTree t){//非递归中序
InitStack(s);
BiTree p=t;
while(p||s.top!=1){
if(p){
Push(s,p->c);
p=p->lchild;
}
else {
pop(s,p->c);
cout<<p;
p=p->rchild;
}
}
}
void PreOrder(BiTree t){//非递归前序
InitStack(s);
BiTree p=t;
while(p||s.top!=1){
if(p){
Push(s,p->c);
p=p->lchild;
}
else {
pop(s,p->c);
cout<<p;
p=p->rchild;
}
}
}
int main() {
BiTree pnew;
BiTree tree = NULL;
ptag_t phead = NULL, ptail = NULL, listpnew = NULL, pcur;
char c;
while (cin >> c) {//输入二叉树 如果输入1就跳出循环(也就视为输入结束)
if (c == '1') break;
pnew = (BiTree)malloc(sizeof(BiTNode));
pnew->c = c;
listpnew = (ptag_t)malloc(sizeof(tag_t));
listpnew->p = pnew;
if (tree == NULL) {
tree = pnew;
phead = listpnew ;
ptail = listpnew;
pcur = listpnew;
} else {
ptail->pnext = listpnew;
ptail = listpnew;
}
if (pcur->p->lchild == NULL)
pcur->p->lchild = pnew;
else if (pcur->p->rchild == NULL) {
pcur->p->rchild = pnew;
pcur = pcur->pnext;
}
}
}