树的先序、后序、层次遍历
#include <iostream>
using namespace std;
typedef struct Branch
{
int cIdx;//当前结点序号
Branch *next;//(邻接矩阵中)指向的下一个树结点
}Branch;
//树的结点
typedef struct
{
int data;
Branch* first;//树结点的第一个孩子存放的地方
}TNode;
//树的先序列遍历
void preOrder(TNode* p,TNode tree[]){
if(p != NULL)
{
visit(p);//输出p
Branch* q;
q = p->first;
while(q != NULL){
//tree是一个数组,此处需要指针,所以用&tree[]
preOrder(&tree[q->cIdx],tree);//走到最左的孩子那里
q = q->next;//回溯的时候,往右走;
}
}
}
//树的后序遍历
void postOrder(TNode* p,TNode tree[]){
if(p != NULL)
{
Branch* q;
q = p->first;
while(q != NULL){
//tree是一个数组,此处需要指针,所以用&tree[]
postOrder(&tree[q->cIdx],tree);//走到最左的孩子那里
q = q->next;//回溯的时候,往右走;
}
visit(p);//输出p
}
}
//树的层次遍历
void level(TNode *tn,TNode tree[])
{
int front,rear;
TNode *que[maxSize];
front = rear = 0;
TNode *p;
if(tn != NULL){
rear = (rear+1) % maxSize;
que[rear] = tn;
while(front)
{
front = (front+1)%maxSize;
p = que[front];
visit(p);
Branch* q = p->first;
while (q != NULL)
{
rear = (rear+1)%maxSize;
que[rear] = &tree[q->cIdx];
q = q->next;
}
}
}
}
int main()
{
return 0;
}