4-11 先序输出叶节点

4-11 先序输出叶结点   (15分)

 

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

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

裁判测试程序样例:

#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 PreorderPrintLeaves( BinTree BT );

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

    return 0;
}
/* 你的代码将被嵌在这里 */

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

Leaf nodes are: D E H I

 

 

 

 

 1 //  4-11 先序输出叶结点
 2 //
 3 //  Created by Haoyu Guo on 05/02/2017.
 4 //  Copyright © 2017 Haoyu Guo. All rights reserved.
 5 //
 6 #include <stdio.h>
 7 #include<iostream>
 8 #include <stdlib.h>
 9 using namespace std;
10 #define OVERFLOW -2
11 typedef char ElementType;
12 typedef struct TNode *Position;
13 typedef Position BinTree;
14 struct TNode{
15     ElementType Data;
16     BinTree Left;
17     BinTree Right;
18 };
19 int CreatBinTree(BinTree &T)//创建二叉树
20 {
21     char ch;//按先序的方式输入
22     cin >> ch;//递归中自然带着一些重复,就不需要循环了
23     if (ch == '#')  T=NULL;
24     else {
25         if (!(T = (BinTree)malloc(sizeof(TNode)))) exit(OVERFLOW);
26         T->Data = ch;
27         CreatBinTree(T->Left);
28         CreatBinTree(T->Right);
29     }
30     return 0;
31 }
32 
33 void PreorderPrintLeaves( BinTree BT );
34 
35 int main()
36 {
37     BinTree BT;
38     CreatBinTree(BT);//创建一个
39     printf("Leaf nodes are:");
40     PreorderPrintLeaves(BT);
41     printf("\n");
42     return 0;
43 }
44 /* 你的代码将被嵌在这里 */
45 void PreorderPrintLeaves( BinTree BT)//先序输出
46 {
47     if(BT==NULL) return;
48     else{
49     if(BT->Left==NULL&&BT->Right==NULL)
50        printf(" %c",BT->Data);
51     PreorderPrintLeaves(BT->Left);
52     PreorderPrintLeaves(BT->Right);
53   }
54 }

 

posted @ 2017-02-05 10:57  女王公园的八神  阅读(385)  评论(0编辑  收藏  举报