Class: CompSci::BinaryTree

Inherits:
NaryTree show all
Defined in:
lib/compsci/tree.rb

Instance Attribute Summary

Attributes inherited from NaryTree

#child_slots

Attributes inherited from Tree

#root

Instance Method Summary collapse

Methods inherited from NaryTree

#open_parent, #open_parent?, #push

Methods inherited from Tree

#bf_search, #df_search, #df_search_generic

Constructor Details

#initialize(klass, val) ⇒ BinaryTree

Returns a new instance of BinaryTree.



130
131
132
# File 'lib/compsci/tree.rb', line 130

def initialize(klass, val)
  super(klass, val, child_slots: 2)
end

Instance Method Details

#to_s(node: nil, width: 80) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/compsci/tree.rb', line 134

def to_s(node: nil, width: 80)
  count = 0
  str = ''
  self.bf_search(node: node) { |n|
    count += 1
    level = Math.log(count, 2).floor
    block_width = width / (2**level)
    str += "\n" if 2**level == count and count > 1
    str += n.to_s.ljust(block_width / 2, ' ').rjust(block_width, ' ')
    false # keep searching to visit every node
  }
  str
end