以二叉链表作存储结构,建立一棵二叉树, 输出该二叉树的先序遍历序列。
二叉链表的类型描述:
typedef char ElemType;
typedef struct BiNode
{ ElemType data;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
输入格式:
输入一个二叉树的先序序列,孩子为空的位置以#
替代。
输出格式:
输出该二叉树的先序遍历序列。输出的遍历序列中字符间均无间隔。
具体格式参看输出样例。
对于下图中给出的二叉树:
输入样例:
ABD##FE###CG#H##I##
输出样例:
ABDFECGHI
代码示例如下:
//链表为存储结构,实现二叉树的创建、遍历
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
//二叉树的存储结构;1个数据域,2个指针域
typedef char ElemType;
typedef struct node{
ElemType data;
struct node *lchild;
struct node *rchild;
}BiNode;
typedef BiNode* BiTree;
//创建二叉树
BiTree CreateTree(){
BiTree T;
char x;
scanf("%c",&x);
if(x=='#') return T=NULL;
if(x=='\n') return T;
else{
T=(BiTree)malloc(sizeof(BiNode));
T->data=x;
T->lchild=CreateTree();
T->rchild=CreateTree();
return T;
}
}
//前序遍历 (递归)
void PreOrderTree(BiTree T){
if(T==NULL) return;
printf("%c",T->data);
PreOrderTree(T->lchild);
PreOrderTree(T->rchild);
}
int main(){
BiTree T;
T=CreateTree(); //建立
PreOrderTree(T); //前序遍历输出
return 0;
}