Class: TreeNode

Inherits:
Struct
  • Object
show all
Defined in:
lib/lander/tree_node.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#leftObject

Returns the value of attribute left

Returns:

  • (Object)

    the current value of left



1
2
3
# File 'lib/lander/tree_node.rb', line 1

def left
  @left
end

#rightObject

Returns the value of attribute right

Returns:

  • (Object)

    the current value of right



1
2
3
# File 'lib/lander/tree_node.rb', line 1

def right
  @right
end

#valObject

Returns the value of attribute val

Returns:

  • (Object)

    the current value of val



1
2
3
# File 'lib/lander/tree_node.rb', line 1

def val
  @val
end

Instance Method Details

#get_levels(levels = [], depth = 0, h = height) ⇒ Object



6
7
8
9
10
11
12
13
14
15
# File 'lib/lander/tree_node.rb', line 6

def get_levels(levels = [], depth = 0, h = height)
  return levels if depth >= h
  levels[depth] ||= []
  levels[depth] << val
  self.left = TreeNode.new('_') unless left
  self.right = TreeNode.new('_') unless right
  left.get_levels(levels, depth + 1, h)
  right.get_levels(levels, depth + 1, h)
  levels
end

#heightObject



2
3
4
# File 'lib/lander/tree_node.rb', line 2

def height
  self ? 1 + [left&.height || 0, right&.height || 0].max : 0
end

#to_sObject



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/lander/tree_node.rb', line 17

def to_s
  puts ""
  levels = get_levels
  levels.each_with_index do |level, depth|
    padding   = ((levels.size - depth) > 1) ? ' ' * ((levels.size - depth) * 2) : (' ' * 3)
    # puts "padding is #{padding.size}"
    level     = level.map { |val| val.nil? ? '_' : val }
    node_vals = level.join(' ' * (levels.size - depth))
    puts "#{padding}#{node_vals}"
  end
  puts ""
end