从文件建立完全二叉树的方法

时间:2022-12-15 17:32:29
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 struct b_node {
 5 
 6     struct b_node *left_child;
 7     
 8     struct b_node *right_child;
 9     
10     struct b_node *parent;
11     
12     int value;
13 };
14 
15 void build_node(struct b_node*,FILE *fp);
16 
17 int main()
18 {
19 
20     int flen = 0;/* the length of file */
21     
22     int* fcontent = NULL;/* the content of the file */
23 
24     int index = 0;
25 
26     struct b_node head;
27     
28     head.parent = NULL;
29 
30     FILE *fp = fopen("data","rb");
31     
32     fscanf(fp,"%d", &head.value);
33 
34     build_node(&head,fp);
35 
36     fclose(fp);
37     
38 }
39 
40 void build_node(struct b_node* current,FILE *fp)
41 {
42     int value = 0;/* value of read */
43     while(fscanf(fp,"%d", &value) != EOF)
44     {
45             current->left_child = (struct b_node *)malloc(sizeof(struct b_node));
46             
47             current->left_child->value = value;
48         
49             current->left_child->parent = current;
50 
51             if(fscanf(fp,"%d",&value) != EOF)
52             {
53                     current->right_child = (struct b_node *)malloc(sizeof(struct b_node));
54 current->right_child->value = value; 55 56 current->right_child->parent = current;
57 build_node(current->left_child,fp); 58 59 build_node(current->right_child,fp); 60 } 61 else 62 { 63 break; 64 } 65 66 67 } 68 69 70 }