建立二叉树的二叉链表存储结构(严6.70)

 

转自:https://blog.csdn.net/zhao2018/article/details/80033358

纯粹是学习一下代码o(∩_∩)o 哈哈

Description
如果用大写字母标识二叉树结点,则一颗二叉树可以用符合下面语法图的字符序列表示。试编写递归程序,由这种形式的字符序列,建立相应的二叉树的二叉链表存储结构(附图见《严蔚敏:数据结构题集(C语言版)》第45页6.70)。

Input
输入如图所示的字符序列。

Output
建立相应二叉树的二成叉链表存储结构,并先序遍历输出。

Sample Input 
A(B(#,D),C(E(#,F),#))
Sample Output
AB#DCE#F#

代码:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <malloc.h>
 4 typedef struct BinTreeNode
 5 {
 6     char  data;
 7     struct BinTreeNode    *lchild;
 8     struct BinTreeNode    *rchild;
 9 };
10 struct BinTreeNode *CreateTree()
11 {
12     char s1,s2;
13     struct BinTreeNode *q;
14     q=(struct BinTreeNode*)malloc(sizeof(struct BinTreeNode));
15     s1=getchar();
16     s2=getchar();
17     q->lchild=NULL;
18     q->rchild=NULL;
19     if(s1==',')
20     {
21         q->data=s2;
22         s1=getchar();
23         if (s1=='(')
24         {
25             q->lchild=CreateTree();
26             q->rchild=CreateTree();
27         }
28     }
29     else
30     {
31         q->data=s1;
32         if (s2=='(')
33         {
34             q->lchild=CreateTree();
35             q->rchild=CreateTree();
36         }
37     }
38     return q;
39 }
40 void PrintBinTree (struct BinTreeNode *p)
41 {
42     printf("%c",p->data);
43     if(p->lchild)
44     {
45         PrintBinTree(p->lchild);
46     }
47     if(p->rchild)
48     {
49         PrintBinTree(p->rchild);
50     }
51 }
52 int main()
53 {
54     BinTreeNode *head;
55     head=CreateTree();
56     PrintBinTree(head);
57     return 0;
58 }

 

posted on 2019-06-19 17:28  华山青竹  阅读(2684)  评论(0编辑  收藏  举报

导航