PTA练习题:二叉树的遍历

悠悠 2023-02-11 04:44 20阅读 0赞

本题要求给定二叉树的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
#include

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

  1. void InorderTraversal( BinTree BT )
  2. {
  3. if(BT != NULL)
  4. {
  5. InorderTraversal(BT->Left);
  6. printf(" %c",BT->Data);
  7. InorderTraversal(BT->Right);
  8. }
  9. }
  10. void PreorderTraversal( BinTree BT )
  11. {
  12. if(BT != NULL)
  13. {
  14. printf(" %c",BT->Data);
  15. PreorderTraversal(BT->Left);
  16. PreorderTraversal(BT->Right);
  17. }
  18. }
  19. void PostorderTraversal( BinTree BT )
  20. {
  21. if(BT != NULL)
  22. {
  23. PostorderTraversal(BT->Left);
  24. PostorderTraversal(BT->Right);
  25. printf(" %c",BT->Data);
  26. }
  27. }
  28. void LevelorderTraversal( BinTree BT )
  29. {
  30. BinTree q[100];
  31. int front = 0;
  32. int rear = 0;
  33. if(BT != NULL)
  34. {
  35. q[rear++] = BT;
  36. }
  37. while(front != rear)
  38. {
  39. if(q[front]->Left != NULL)
  40. {
  41. q[rear++] = q[front]->Left;
  42. }
  43. if(q[front]->Right != NULL)
  44. {
  45. q[rear++] = q[front]->Right;
  46. }
  47. printf(" %c",q[front++]->Data);
  48. }
  49. }

发表评论

表情:
评论列表 (有 0 条评论,20人围观)

还没有评论,来说两句吧...

相关阅读