Class: LambdaGem::Node

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = nil) ⇒ Node

Returns a new instance of Node.



9
10
11
# File 'lib/node.rb', line 9

def initialize data=nil
  @data, @left, @right = data, nil, nil
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



7
8
9
# File 'lib/node.rb', line 7

def data
  @data
end

#leftObject

Returns the value of attribute left.



7
8
9
# File 'lib/node.rb', line 7

def left
  @left
end

#rightObject

Returns the value of attribute right.



7
8
9
# File 'lib/node.rb', line 7

def right
  @right
end

Instance Method Details

#leaf?Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/node.rb', line 13

def leaf?
  @left.nil? and @right.nil?
end

#purgeObject



17
18
19
# File 'lib/node.rb', line 17

def purge 
  @data, @left, @right = nil, nil, nil
end

#traverse(order = :infix) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/node.rb', line 21

def traverse order=:infix
  if leaf?
    @data
  else
    left_child, right_child = @left.traverse(order), @right.traverse(order)

    strs = case order
      when :prefix then [@data, left_child, right_child]
      when :infix then [left_child, @data, right_child]
      when :postfix then [left_child, right_child, @data]
      else []
    end   
    "(" + strs.join(" ") + ")"
  end             
end