Binary tree in C
i want to obtain the binary code of all the leafes of a bin tree. have any ideea on how to do that?
i code 0 for left and 1 of right. Thank you! |
Quote:
Look up "tree traversal." I'll give you hint, if you write a lot of code for this then you're wrong. The root node is a special case, every other node you are building a string which will be printed when you hit a leaf. Oh, and remember "recursion!" |
i'm trying to implement the huffman compresion algorithm... and i don't know how to obtain the binary code for each character. And no.. the standart traversals of a tree don't work in this case.
|
I've written Huffman, and it really is a basic traversal.
With this, you should be able to flesh it out. pseudo-code: Code:
void buildEncode(Node n, string code) |
this i don't understand
Code:
string leftCode = code + "0"; |
This bit here:
The function, buildEncode, takes in the parameter "code" void buildEncode(Node n, string code) So, "code" is local to the function, only one instance. That bit is very much like C. That variable symbolizes the "huffman code so far." If you get to those statements, you know you aren't on a leaf, therefore you will need to visit at least one more node. Actually, there is one more case, to keep you from spinning on it, I'll add it. Check for null: Code:
void buildEncode(Node n, string code) |
you mean something like this?
Code:
void preordine(tree a,char bin[100]) |
Quote:
Well, add the NULL check I made in the last post. If this code: if((a->leg[0]==NULL)&&(a->leg[1]==NULL)) is equivalent to: if(isLeaf(n)) Then this is close. However, you have a mistake. You must include "bin" in both places. You should have something closer to Code:
else |
Code:
void preordine(tree a,char bin[100]) |
No problem. =)
Again, its kind of early, but I think you need to make sure "a" is not null before you make those two checks. |
the tree will always have an element in it. and when it is built i use calloc that initializes all poiners with null. so i think it will never be null.
|
Right, the only problem would be if a parent had only one child, say a left child, then after this line:
preordine(a->leg[1],d); When the preordine from this call runs, "a" will be null and you will get a seg-fault. Without the null check on "a," the code will only work if all parents have exactly two children. |
uuuuuf.... right again.
now something a little offtopic... my program only works on text files. when you did the huffman how did you read the file ? |
Well, just use the standard mechanisms. The C++ way would be to use fstream, like so:
Code:
void buildFreqTable(char *input) http://www.cprogramming.com/tutorial/cfileio.html |
yes that is what i used but it doesn't work with binary files. for reading i used:
Code:
FILE *f=fopen("fis.in","rb"); |
All times are GMT -5. The time now is 01:41 AM. |