Class: CompSci::Tree

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

Direct Known Subclasses

NaryTree

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, val) ⇒ Tree

Returns a new instance of Tree.



63
64
65
# File 'lib/compsci/tree.rb', line 63

def initialize(klass, val)
  @root = klass.new val
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root.



61
62
63
# File 'lib/compsci/tree.rb', line 61

def root
  @root
end

Instance Method Details

#bf_search(node: nil, &blk) ⇒ Object



77
78
79
80
81
82
83
84
85
86
# File 'lib/compsci/tree.rb', line 77

def bf_search(node: nil, &blk)
  node ||= @root
  destinations = [node]
  while !destinations.empty?
    node = destinations.shift
    return node if yield node
    destinations += node.children
  end
  nil
end

#df_search(node: nil, &blk) ⇒ Object



67
68
69
70
71
72
73
74
75
# File 'lib/compsci/tree.rb', line 67

def df_search(node: nil, &blk)
  node ||= @root
  return node if yield node
  node.children.each { |c|
    stop_node = self.df_search(node: c, &blk)
    return stop_node if stop_node
  }
  nil
end

#df_search_generic(node: nil, &blk) ⇒ Object



88
89
90
91
92
93
# File 'lib/compsci/tree.rb', line 88

def df_search_generic(node: nil, &blk)
  # Perform pre-order operation
  # children.each { Perform in-order operation }
  # Perform post-order operation
  puts "not defined yet"
end