版权声明:转载请注明 https://blog.csdn.net/NCC__dapeng/article/details/83818028
保持先序遍历不变,加一个特殊判断是否左右节点为空即可。(注意叶子结点一定是左右孩子均为空)
下面给出AC代码:
#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) return;
if(BT->Left==NULL&&BT->Right==NULL)
{
printf(" %c",BT->Data);
return;
}
else
{
PreorderPrintLeaves(BT->Left);
PreorderPrintLeaves(BT->Right);
}
}