您的当前位置:首页正文

7-3 数据结构考题 二叉树的遍历-先序分

来源:九壹网

以二叉链表作存储结构,建立一棵二叉树, 输出该二叉树的先序遍历序列。

二叉链表的类型描述:

typedef char ElemType;
typedef  struct  BiNode
{  ElemType  data;
    struct  BiNode   *lchild,*rchild;
}BiNode,*BiTree;  

输入格式:

输入一个二叉树的先序序列,孩子为空的位置以#替代。

输出格式:

输出该二叉树的先序遍历序列。输出的遍历序列中字符间均无间隔。
具体格式参看输出样例。

对于下图中给出的二叉树:

输入样例:

ABD##FE###CG#H##I##

输出样例:

ABDFECGHI

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

栈限制

8192 KB

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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;
}

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Top