50251. Decode with a Huffman tree
難度:3/51
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "HuffmanDecoding.h"
// typedef struct Node {
// char symbol[5];
// int frequency;
// struct Node *left, *right;
// }Node;
void HuffmanDecoding(Node *root, char *data){
Node* now = root;
int n = strlen(data);
#ifdef SPACE
char c = ' ';
#endif
#ifdef NEWLINE
char c = '\n';
#endif
for(int i = 0; i < n; i++){
if(data[i] == '0') now = now->left;
else if(data[i] == '1') now = now->right;
if(now->left == NULL && now->right == NULL) now = root;
}
if(now != root){
printf("-1%c", c);
return;
}
for(int i = 0; i < n; i++){
if(data[i] == '0'){
now = now->left;
}
else if(data[i] == '1'){
now = now->right;
}
if(now->left == NULL && now->right == NULL){
printf("%s%c", now->symbol, c);
now = root;
}
}
}