分数 5
作者 DS课程组
单位 临沂大学
本题要求实现给定的二叉树的三种遍历。
函数接口定义:
void Preorder(BiTree T);
void Inorder(BiTree T);
void Postorder(BiTree T);
T是二叉树树根指针,Preorder、Inorder和Postorder分别输出给定二叉树的先序、中序和后序遍历序列,格式为一个空格跟着一个字符。
其中BinTree结构定义如下:
typedef char ElemType;
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 Preorder(BiTree T);
void Inorder(BiTree T);
void Postorder(BiTree T);
int main()
{
BiTree T = Create();
printf("Preorder:"); Preorder(T); printf("\n");
printf("Inorder:"); Inorder(T); printf("\n");
printf("Postorder:"); Postorder(T); printf("\n");
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
输入为由字母和'#'组成的字符串,代表二叉树的扩展先序序列。例如对于如下二叉树,输入数据:
AB#DF##G##C##
输出样例(对于图中给出的树):
Preorder: A B D F G C
Inorder: B F D G A C
Postorder: F G D B C A
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
C程序如下:
void Preorder(BiTree T){
if(T == NULL){
return;
}
printf(" %c", T->data); // 先访问根节点
Preorder(T->lchild); // 然后递归遍历左子树
Preorder(T->rchild); // 最后递归遍历右子树
}
void Inorder(BiTree T){
if(T == NULL){
return;
}
Inorder(T->lchild); // 先递归遍历左子树
printf(" %c", T->data); // 然后访问根节点
Inorder(T->rchild); // 最后递归遍历右子树
}
void Postorder(BiTree T){
if(T == NULL){
return;
}
Postorder(T->lchild); // 先递归遍历左子树
Postorder(T->rchild); // 然后递归遍历右子树
printf(" %c", T->data); // 最后访问根节点
}