建立二叉樹的二叉鏈表存儲結構(嚴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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM