Class: BinarySearchTree

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

Instance Method Summary collapse

Constructor Details

#initializeBinarySearchTree

Returns a new instance of BinarySearchTree.



5
6
7
# File 'lib/honey_mushroom/binary_search_tree.rb', line 5

def initialize
  @head = nil
end

Instance Method Details

#delete(value) ⇒ Object



29
30
31
# File 'lib/honey_mushroom/binary_search_tree.rb', line 29

def delete(value)
  delete_node(value, node=@head)
end

#include?(value, node = @head) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/honey_mushroom/binary_search_tree.rb', line 25

def include?(value, node=@head)
  !!search(value, node)
end

#insert(value, node = @head) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/honey_mushroom/binary_search_tree.rb', line 33

def insert(value, node=@head)
  if node.value < value
    insert_right(value, node)
  elsif node.value > value
    insert_left(value, node)
  else
    return false
  end
end

#search(value, node = @head) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/honey_mushroom/binary_search_tree.rb', line 13

def search(value, node=@head)
  if value == node.value
    return node.value
  elsif value < node.value
    search(value, node.left) unless node.left.nil?
  elsif value > node.value
    search(value, node.right) unless node.right.nil?
  else
    return nil
  end
end

#set_head(value) ⇒ Object



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

def set_head(value)
  @head = Node.new({value: value, left: nil, right: nil})
end