本题要求实现一个函数,按照中序遍历的顺序输出给定二叉树的叶结点。
函数接口定义:
void InorderPrintLeaves( BiTree T);
T是二叉树树根指针,InorderPrintLeaves按照中序遍历的顺序输出给定二叉树T的叶结点,格式为一个空格跟着一个字符。
其中BiTree结构定义如下:
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree Create();/* 细节在此不表 */
void InorderPrintLeaves( BiTree T);
int main()
{
BiTree T = Create();
printf("Leaf nodes are:");
InorderPrintLeaves(T);
return 0;
}
/* 你的代码将被嵌在这里 */
输出样例(对于图中给出的树):
Leaf nodes are: F G C
建树代码:
BiTree Create()
{
char ch;
scanf("%c",&ch);
if(ch=='#') return NULL;
BiTree T = (BiTree)malloc(sizeof(struct BiTNode));
T->data = ch;
T->lchild = Create();
T->rchild = Create();
return T;
}
中序输出叶子结点
void InorderPrintLeaves( BiTree T)
{
if(T==NULL) return ;
InorderPrintLeaves(T->lchild);
if(T->lchild==NULL&&T->rchild==NULL)
printf(" %c",T->data);
InorderPrintLeaves(T->rchild);
}
在输入的时候,如果说某节点的子节点为空,那么用#表示,这一支子树也就结束了;如果说某一个非空节点它的左右孩子都为空,那么都写上# (非常重要,这是后面程序判断的依据,程序就是按照#和字符的分布进行判断的)
AB#DF##G##C##
Leaf nodes are: F G C