遍历方法共有四种,前篇已经介绍过,性质上分为深度优先和广度优先
深度优先
先访问结点的孩子,访问完孩子的所有子树再来到下一个孩子,左右子树与结点的访问顺序不同决定出三种不同遍历方法
void Preorder(BinaryTree* T){
if (T==NULL) return;
cout<<T->data<<" ";
Preorder(T->leftchild);//遍历左子树;
Preorder(T->rightchild);//再遍历右子树
}
void Inorder(BinaryTree* T){
if (T==NULL) return;
Inorder(T->leftchild);//先遍历左子树
cout<<T->data<<" ";
Inorder(T->rightchild);//再遍历右子树
}
void Postorder(BinaryTree* T){
if (T==NULL) return;
Postorder(T->leftchild);
Postorder(T->rightchild);
cout<<T->data<<" ";
}
三种方式运行结果
广度优先
即先访问同一层级的结点,然后移到下一层访问,称为层序遍历
需要用到队列,首先将根结点入队,队列非空即将队列元素打印出来,再将它的孩子入队,在访问左子树时再将它的孩子入队,以此类推,可以让结点按从上至下的层级、从左到右的顺序依次入队出队,实现层序遍历。
入队
void enQueue(BinaryTree* data) {
Queue* l=Q;
Queue* temp=(Queue8)malloc(sizeof(Queue));
temp->data=data;
temp->next=NULL;
while (l->next!=NULL)
l=l->next;
l->next=temp;
temp->pre=l;
}
出队
Queue* deQueue() {
if (isEmpty(Q))
return NULL;
else {
Queue* temp=Q->next;
if (Q->next->next!=NULL)
Q->next->next->pre=Q;
Q->next=Q->next->next;
return temp;
}
}
层序遍历
void Levelorder(BinaryTree* T) {
if (T==NULL)
return;
enQueue(T);//将不为空的结点入队
while (!isEmpty(Q)) {
Queue* temp=deQueue();
cout<<temp->data->data<<" ";//将结点出队
if (temp->data->leftchild!=NULL)//将不为空的孩子入队
enQueue(temp->data->leftchild);
if (temp->data->rightchild!=NULL)
enQueue(temp->data->rightchild);
}
}
完整代码
#include <bits/stdc++.h>
using namespace std;
//定义结构体
typedef struct Tree {
struct Tree* leftchild;
char data;
struct Tree* rightchild;
} BinaryTree;
typedef struct queue {
struct queue* pre;
BinaryTree* data;
struct queue* next;
}Queue;
Queue* Q=(Queue*)malloc(sizeof(Queue));
bool isEmpty(Queue* Q) {
return Q->next==NULL;
}
//创建二叉树
void createtree(BinaryTree** T){
char data;
cin>>data;
if(data=='#') *T=NULL;
else {
*T=(BinaryTree*)malloc(sizeof(BinaryTree));
(*T)->data=data;
createtree(&((*T)->leftchild));
createtree(&((*T)->rightchild));
}
}
//入队
void enQueue(BinaryTree* data) {
Queue* l=Q;
Queue* temp=(Queue*)malloc(sizeof(Queue));
temp->data=data;
temp->next=NULL;
while (l->next!=NULL)
l=l->next;
l->next=temp;
temp->pre=l;
}
//出队
Queue* deQueue() {
if (isEmpty(Q))
return NULL;
else {
Queue* temp=Q->next;
if (Q->next->next!=NULL)
Q->next->next->pre=Q;
Q->next=Q->next->next;
return temp;
}
}
//层序遍历
void Levelorder(BinaryTree* T) {
if (T==NULL)
return;
enQueue(T);
while (!isEmpty(Q)) {
Queue* temp=deQueue();
cout<<temp->data->data<<" ";
if (temp->data->leftchild!=NULL)
enQueue(temp->data->leftchild);
if (temp->data->rightchild!=NULL)
enQueue(temp->data->rightchild);
}
}
int main() {
BinaryTree* T;
createtree(&T);
cout<<endl;
Levelorder(T);
return 0;
}