-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree2book.m
More file actions
36 lines (30 loc) · 935 Bytes
/
tree2book.m
File metadata and controls
36 lines (30 loc) · 935 Bytes
1
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
% tree2book.m
% Noam Siegel
% January 24, 2022
function codebook = tree2book(root)
% Parse a binary tree representing a huffman codebook
if (isequal(root.left, []) && isequal(root.right, []))
codebook = struct('lower_edge', root.lower_edge, 'code', '0');
return
end
if (isequal(root.left, []))
codebook = tree2book(root.right);
return
end
if (isequal(root.right, []))
codebook = tree2book(root.left);
return
end
% recursively find left and right children codebooks
lcodebook = tree2book(root.left);
rcodebook = tree2book(root.right);
% append 0 and 1 to codewords
lcode = {lcodebook.code};
rcode = {rcodebook.code};
new_lcode = concatzero(lcode);
[lcodebook.code] = new_lcode{:};
new_rcode = concatone(rcode);
[rcodebook.code] = new_rcode{:};
% concat structs
codebook = [lcodebook; rcodebook];
end