本题要求实现按从左到右顺序打印二叉树的指定层次的结点序列。
函数接口定义:
void PrintLevel(BiTree T,int n);
T是二叉树树根指针,n为指定打印的层次,PrintLevel函数按从左到右顺序输出二叉树的指定层次的结点序列,格式为一个字符后面跟着一个空格。
其中BinTree结构定义如下:
typedef char ElementType;
typedef struct BiTNode {
ElementType data;
struct BiTNode *lchild;
struct BiTNode *rchild;
}BiTNode, *BiTree;
裁判测试程序样例:
#include <stdio.h> #include <stdlib.h> typedef char ElementType; typedef struct BiTNode { ElementType data; struct BiTNode *lchild; struct BiTNode *rchild; }BiTNode, *BiTree; BiTree Create();/* 细节在此不表 */ void PrintLevel(BiTree T, int n); int main() { int n; BiTree T = Create(); scanf("%d", &n); PrintLevel(T, n); printf("\n"); return 0; } /* 你的代码将被嵌在这里 */
输入样例:
对于图中给出的二叉树,输入数据为两行,第一行是扩展的先序序列,第二行是要输出的层次数:
AB#DF##G##C##
2
输出样例:
B C
代码长度限制
16 KB
时间限制
400 ms
内存限制
题解:
void PrintLevel(BiTree T,int n)
{
if(!T||n<=0) return;//进行判空和输出后的结束函数
if(n==1) printf("%c ",T->data);
else
{
PrintLevel(T->lchild,n-1);
PrintLevel(T->rchild,n-1);
}
}
通过令n-1,来表示二叉树层次的相加,当n=1时即为所求的层次,然后if语句成立进行输出