• 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("
    ");
    
        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("
    ");
    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 }
  • 相关阅读:
    逆向随笔
    Test for Required Behavior, Not Incidental Behavior
    Volley 解析
    使用Apache JMeter压測Thrift
    hdu 5289 Assignment(给一个数组,求有多少个区间,满足区间内的最大值和最小值之差小于k)
    ORACLE 11G在存储过程里面遍历游标, 调用job任务定时运行
    Netlink 内核实现分析(二):通信
    6.3 cmath--数学函数
    CodeChef Little Elephant and Mouses [DP]
    BZOJ 1758: [Wc2010]重建计划 [暂时放弃]
  • 原文地址:https://www.cnblogs.com/guohaoyu110/p/6367153.html
Copyright © 2020-2023  润新知