先序输出叶节点

来源:互联网 发布:线程优化 编辑:程序博客网 时间:2024/05/08 21:37

先序输出叶节点

题目描述:

本题要求按照先序遍历的顺序输出给定二叉树的叶结点。
函数接口定义:
void PreorderPrintLeaves( BinTree BT );
其中BinTree结构定义如下:
typedef struct TNode *Position;typedef Position BinTree;struct TNode{    ElementType Data;    BinTree Left;    BinTree Right;};
函数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

代码:

void PreorderPrintLeaves( BinTree BT ){    if(BT)    {        if(BT->Left)            PreorderPrintLeaves(BT->Left);        if(BT->Right)            PreorderPrintLeaves(BT->Right);        if(NULL == BT->Left && NULL == BT->Right)            printf(" %c",BT->Data);    }}

代码分析:

用递归的方式进行,但是输出的时候要进行控制,确保该节点是叶子节点。

原创粉丝点击