PTA练习题:先序输出叶结点

忘是亡心i 2023-02-11 04:45 82阅读 0赞

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

函数接口定义:

void PreorderPrintLeaves( BinTree BT );
其中BinTree结构定义如下:

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
函数PreorderPrintLeaves应按照先序遍历的顺序输出给定二叉树BT的叶结点,格式为一个空格跟着一个字符。

裁判测试程序样例:

#include
#include

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};

BinTree CreatBinTree(); /* 实现细节忽略 */
void PreorderPrintLeaves( BinTree BT );

int main()
{
BinTree BT = CreatBinTree();
printf(“Leaf nodes are:”);
PreorderPrintLeaves(BT);
printf(“\n”);

  1. return 0;

}
/* 你的代码将被嵌在这里 */
输出样例(对于图中给出的树):
在这里插入图片描述

Leaf nodes are: D E H I

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

发表评论

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

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

相关阅读

    相关 单链表删除--PTA

    本题要求实现两个函数,分别将读入的数据存储为单链表、将链表中所有存储了某给定值的结点删除。链表结点定义如下: struct ListNode {