【PTA】6-11 先序输出叶结点 (15分)

【PTA】6-11 先序输出叶结点 (15分)

函数接口定义:

void PreorderPrintLeaves( BinTree BT );

其中BinTree结构定义如下:

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

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

裁判测试程序样例:

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

输出样例:

Leaf nodes are: D E H I

函数实现细节:

 1 #define MAXSIZE 30
 2 void PreorderPrintLeaves( BinTree BT ){
 3     if(BT){
 4         BinTree stack[MAXSIZE];int top=-1;
 5         while(top!=-1||BT){
 6             while(BT){stack[++top]=BT;BT=BT->Left;}
 7             if(top!=-1){
 8                 BT=stack[top--];
 9                 if(BT->Left==NULL&&BT->Right==NULL)printf(" %c",BT->Data);
10                 BT=BT->Right;
11             }
12         }
13          
14     }
15 }
原文地址:https://www.cnblogs.com/wyjgr/p/13073633.html