A Branch has, in addition to the attributes of a Node, a sequence of two Node objects called subtrees.
Its weight and width are the sums of the weights and widths, respectively, of its subtrees.
Its height is 1 plus the maximum of the heights of its subtrees.
Its offset the average of the offsets of the two subtrees, after their bounding boxes are merged into one.
Assign two Node objects (subtrees) to a branch node.
The weight and width are the sums of the weights and widths, respectively, of the subtrees.
The height is 1 plus the maximum of the heights of the subtrees.
The offset the average of the offsets of the two subtrees, after their bounding boxes are merged into one.
# File huffman_tree.rb, line 163 def initialize(weighted_tree0, weighted_tree1) @subtrees = [weighted_tree0, weighted_tree1] raise ArgumentError, 'Not a Node' unless @subtrees[0].is_a? Node raise ArgumentError, 'Not a Node' unless @subtrees[1].is_a? Node weight = @subtrees.inject(0) { |sum, t| sum + t.weight } width = @subtrees.inject(0) { |sum, t| sum + t.width } height = 1 + [@subtrees[0].height, @subtrees[1].height].max offset = @subtrees[0].offset + @subtrees[1].offset offset = (offset + @subtrees[0].width) / 2.0 super(weight, width, height, offset) end
Reference a subtree of the Branch node.
# File huffman_tree.rb, line 186 def [](index) @subtrees[index.to_i] end
Generate JavaScript to draw tree rooted at this node.
# File huffman_tree.rb, line 193 def draw(bits='') offset = @subtrees.map { |t| t.offset } width = @subtrees.map { |t| t.width } " #{draw_link(bits)} draw_line(1, #{offset[0]}, 1, #{offset[1] + width[0]}); translate(1, 0); #{@subtrees[0].draw(bits+'0')} translate(0, #{width[0]}); #{@subtrees[1].draw(bits+'1')} translate(-1, #{-width[0]}); " end
Length of the longest symbol in the deepest level of tree.
# File huffman_tree.rb, line 178 def margin(deepest, depth=0) [@subtrees[0].margin(deepest, depth+1), @subtrees[1].margin(deepest, depth+1)].max end