6-9 二叉树的遍历
本题要求给定二叉树的4种遍历。
函数接口定义:
void InorderTraversal( BinTree BT ); void PreorderTraversal( BinTree BT ); void PostorderTraversal( BinTree BT ); void LevelorderTraversal( BinTree BT );
其中BinTree结构定义如下:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
要求4个函数分别按照访问顺序打印出结点的内容,格式为一个空格跟着一个字符。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
BinTree CreatBinTree(); /* 实现细节忽略 */
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );
int main()
{
BinTree BT = CreatBinTree();
printf("Inorder:"); InorderTraversal(BT); printf("\n");
printf("Preorder:"); PreorderTraversal(BT); printf("\n");
printf("Postorder:"); PostorderTraversal(BT); printf("\n");
printf("Levelorder:"); LevelorderTraversal(BT); printf("\n");
return 0;
}
/* 你的代码将被嵌在这里 */
输出样例(对于图中给出的树):
Inorder: D B E F A G H C I Preorder: A B D F E C G H I Postorder: D E F B H G I C A Levelorder: A B C D F G I E H
注意层序遍历的写法,此处使用数组了模拟队列(queue)
使用队列实现层序遍历的方法如下:
void LevelorderTraversal( BinTree BT ){
#include<queue>
if(BT==NULL){
return;
}
queue<Position>Q;
Q.push(BT);
while(!Q.empty()){
Position = Q.front();
printf(" %c",Position->Data);
Q.pop();
if(Q->Left!=NULL){
Q->push(Q->Left);
}
if(Q->Right!=NULL){
Q->push(Q->Right);
}
}
}
补充:使用队列实现BFS、使用堆来实现DFS
void BFS(Node *pRoot)
{
if (pRoot==NULL)
return;
queue<Node*> Q;
Q.push(pRoot);
while(!Q.empty())
{
Node *node = Q.front();
cout<<node->nVal<<"->";
if (node->pLeft!=NULL)
{
Q.push(node->pLeft);
}
if (node->pRight!=NULL)
{
Q.push(node->pRight);
}
Q.pop();
}
cout<<endl;
}
void DFS_Iterative(Node* pRoot)
{
if (pRoot==NULL)
return;
stack<Node*> S;
S.push(pRoot);
while (!S.empty())
{
Node *node=S.top();
cout<<node->nVal<<",";
S.pop();
if (node->pRight!=NULL)
{
S.push(node->pRight);
}
if (node->pLeft!=NULL)
{
S.push(node->pLeft);
}
}
}
代码:
void InorderTraversal( BinTree BT ){
if(BT==NULL){
return;
}
InorderTraversal(BT->Left);
printf(" %c",BT->Data);
InorderTraversal(BT->Right);
}
void PreorderTraversal( BinTree BT ){
if(BT==NULL){
return;
}
printf(" %c",BT->Data);
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
}
void PostorderTraversal( BinTree BT ){
if(BT==NULL){
return;
}
PostorderTraversal(BT->Left);
PostorderTraversal(BT->Right);
printf(" %c",BT->Data);
}
void LevelorderTraversal( BinTree BT ){
if(BT==NULL){
return;
}
BinTree Q[100];
int head=0,last=0;
Q[last++]=BT;
while(head<last){
BinTree temp=Q[head++];
printf(" %c",temp->Data);
if(temp->Left!=NULL){
Q[last++]=temp->Left;
}
if(temp->Right!=NULL){
Q[last++]=temp->Right;
}
}
}

浙公网安备 33010602011771号