Class: Node

Inherits:
Object
  • Object
show all
Defined in:
lib/huffman_coding/node.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, weight, left = nil, right = nil) ⇒ Node

Returns a new instance of Node.



6
7
8
9
10
11
12
# File 'lib/huffman_coding/node.rb', line 6

def initialize(value, weight, left = nil, right = nil)
  @value = value
  @weight = weight
  @left = left
  @right = right
  @leaf = (@left == nil && @right == nil)
end

Instance Attribute Details

#weightObject (readonly)

Returns the value of attribute weight.



4
5
6
# File 'lib/huffman_coding/node.rb', line 4

def weight
  @weight
end

Instance Method Details

#<=>(other) ⇒ Object



23
24
25
# File 'lib/huffman_coding/node.rb', line 23

def <=>(other)
  @weight <=> other.weight
end

#traverse(code, hash) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/huffman_coding/node.rb', line 14

def traverse(code, hash)
  if @leaf
    hash[@value] = code
  else
    @left.traverse("#{code}1", hash)
    @right.traverse("#{code}0", hash)
  end
end