用二叉鏈表建立二叉樹


 1 #include<stdio.h> 
 2 #include<stdlib.h>
 3 typedef struct node
 4 {
 5     int data;
 6     struct node *l,*r;
 7     
 8 }tree;
 9 tree* Creattree(void)//層次建立二叉樹 
10 {
11     int data,front=1,rear=0; 
12     tree* t, *root, *q[1001];
13   while(scanf("%d", &data),data!=-1) 
14   { 
15   if(data==0) 
16   t = NULL; 
17   else 
18   { 
19   t=(tree*)malloc(sizeof(tree));
20   t->data=data;
21   t->l=NULL; 
22   t->r=NULL; 
23   } 
24   rear++;
25   q[rear]=t;//元素入隊 
26   if(rear==1)
27   root= t;//建立根結點 
28   else
29  {
30   if(q[front]!=NULL) 
31   { 
32   if(rear%2==0)
33   q[front]->l = t;//偶數給左 
34   else 
35   q[front]->r = t;//奇數給右 
36   } 
37   if(rear%2==1)//保證兩個數都掛上樹了再換下一個結點 
38   front++;
39 }
40 } 
41 return root;
42 }
43 void preorder(tree *p)//這里只舉例前序遍歷,中序和后序前一張有 
44 {
45     if(p==NULL)
46    return;
47    printf(" %d", p->data);
48    preorder(p->l);
49    preorder(p->r);
50 }
51 int main()
52 {
53     tree *t;
54     int n;
55     scanf("%d",&n);
56     while(n--)
57     {
58         t=Creattree();
59         preorder(t);
60         printf("\n");
61     }
62     return 0;
63 }

 


免責聲明!

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



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