6-3 先序输出叶结点 (15 分)

太过爱你忘了你带给我的痛 2022-04-22 03:46 208阅读 0赞

本题要求按照先序遍历的顺序输出给定二叉树的叶结点。

函数接口定义:

  1. void PreorderPrintLeaves( BinTree BT );

其中BinTree结构定义如下:

  1. typedef struct TNode *Position;
  2. typedef Position BinTree;
  3. struct TNode{
  4. ElementType Data;
  5. BinTree Left;
  6. BinTree Right;
  7. };

函数PreorderPrintLeaves应按照先序遍历的顺序输出给定二叉树BT的叶结点,格式为一个空格跟着一个字符。

裁判测试程序样例:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef char ElementType;
  4. typedef struct TNode *Position;
  5. typedef Position BinTree;
  6. struct TNode{
  7. ElementType Data;
  8. BinTree Left;
  9. BinTree Right;
  10. };
  11. BinTree CreatBinTree(); /* 实现细节忽略 */
  12. void PreorderPrintLeaves( BinTree BT );
  13. int main()
  14. {
  15. BinTree BT = CreatBinTree();
  16. printf("Leaf nodes are:");
  17. PreorderPrintLeaves(BT);
  18. printf("\n");
  19. return 0;
  20. }
  21. /* 你的代码将被嵌在这里 */

在这里插入图片描述

输出样例(对于图中给出的树):

  1. Leaf nodes are: D E H I

代码:

  1. void PreorderPrintLeaves( BinTree BT )
  2. {
  3. if(BT){
  4. if(!BT->Left&&!BT->Right)printf(" %c",BT->Data);
  5. if(BT->Left)PreorderPrintLeaves(BT->Left);
  6. if(BT->Right)PreorderPrintLeaves(BT->Right);
  7. }
  8. }

发表评论

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

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

相关阅读