本题要求按照先序遍历的顺序输出给定二叉树的叶结点。
函数接口定义:
void PreorderPrintLeaves( BinTree BT );
函数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;
}
/* 你的代码将被嵌在这里 */
**
实现代码:
**
void PreorderPrintLeaves( BinTree BT ){
if(BT!=NULL){ //若节点不为空
if(BT->Left==NULL && BT->Right==NULL){//判断是否为叶节点
printf(" %c", BT->Data); //按题目格式输出数据
return;
}
else{
PreorderPrintLeaves(BT->Left);//递归遍历左节点
PreorderPrintLeaves(BT->Right);//递归遍历右节点
}
}
}
该博客主要介绍如何使用先序遍历的方法,递归地遍历二叉树并输出所有的叶节点。在给定的C语言代码中,通过检查每个节点的左右子节点是否为空来判断是否为叶节点,并按照要求的格式打印数据。
930

被折叠的 条评论
为什么被折叠?



