Example of a binary file I have:
0000000: 11111011 11111111 11111111 11111111 00000001 11111100 ......
0000006: 11111111 11111111 11111111 00000001 11111101 11111111 ......
000000c: 11111111 11111111 00000001 11111110 11111111 11111111 ......
0000012: 11111111 00000001 11111111 11111111 11111111 11111111 ......
0000018: 00000001 00000000 00000000 00000000 00000000 00000001 ......
000001e: 00000001 00000000 00000000 00000000 00000001 00000010 ......
0000024: 00000000 00000000 00000000 00000001 00000101 00000000 ......
000002a: 00000000 00000000 00000001 00000100 00000000 00000000 ......
0000030: 00000000 00000000 ..
This is txt representation of that same file where each line represents a node:
-5 1
-4 1
-3 1
-2 1
-1 1
0 1
1 1
2 1
5 1
4 0
Where the first number is the value of the node. And the next number represents how many children the node has. 0 means no children. 1 means one right child. 2 means one left child. 3 means two children.
This is the structure of a node:
struct Tnode {
int key;
char child;
struct Tnode * left;
struct Tnode * right;
} Tnode;
Currently for each node I am trying to use fread twice, one to get the int key, and then to get the char child. But how can I actually build the tree given that the binary tree contains the pre-order traversal ? The first node we encounter has to be the root node. Since it has a 1 next to it, it will only have a right child (this will be stored in char child). Therefore, the next node has to be the right child of that, as and so on. Basically, with this example, the right keeps on going on the right until it ends with 4. But I am having trouble building it. Any tips?
You can solve this probem using recursion :
You create a function process_node
which takes one parameter, which is the address of the pointer which should point to the new node. When calling the function for the first time, this will be the address of the pointer to the root node.
The function process_node
does the following:
struct Tnode
.int key
and the char child
from file and writes that information to the newly allocated struct Tnode
.process_node
will now recursively calls itself, but the function parameter of this function call will this time be the address of its right
member variable. That way, the newly called function will write to that address instead. If the node does not have a right child, then the right
member variable is set to NULL
.After all recursive function calls return, you should have a fully built binary tree.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.