This question requires outputting the leaf nodes of a given binary tree in the order of preorder traversal.
Function interface definition:
void PreorderPrintLeaves( BinTree BT );
where BinTree
the structure is defined as follows:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
The function PreorderPrintLeaves
should output the leaf nodes of the given binary tree in the order of preorder traversal BT
, formatted as a space followed by a character.
Sample referee test procedure:
#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;
}
/* 你的代码将被嵌在这里 */
Sample output (for the tree given in the figure):
Leaf nodes are: D E H I
代码长度限制16 KB
时间限制400 ms
内存限制64 MB
Answer:
void PreorderPrintLeaves( BinTree BT )
{
if(BT){
if(!BT->Left&&!BT->Right)
printf(" %c",BT->Data);
PreorderPrintLeaves(BT->Left);
PreorderPrintLeaves(BT->Right);
}
}