I was tasked with building three individual methods; one to create a Binary Search Tree (BST), one to carry out a Breadth First Search (BFS), and one to carry out a Depth First Search (DFS).
Create Binary Tree
class Node
attr_accessor :value, :left, :right
def initialize(value)
@value = value
end
end
def build_tree(array, *indices)
array.sort.uniq!
mid = (array.length-1)/2
first_element = indices[0]
last_element = indices[1]
if !first_element.nil? && first_element >last_element
return nil
end
root = Node.new(array[mid])
root.left = build_tree(array[0..mid-1], 0, mid-1)
root.right = build_tree(array[mid+1..-1], mid+1, array.length-1)
return root
end
Breadth First Search
def breadth_first_search(search_value, tree)
queue = [tree]
visited = [tree]
while !queue.empty?
current = queue.shift
visited << current
left, right = current.left, current.right
if current.value == search_value
puts current
exit
end
if !left.nil? && !visited.include?(left)
if left.value == search_value
puts left
exit
else
visited << left
queue << left
end
end
if !right.nil? && !visited.include?(right)
if right.value == search_value
puts right
exit
else
visited << right
queue << right
end
end
end
puts "nil"
end
Depth First Search
def depth_first_search(search_value, tree)
stack = [tree]
visited = [tree]
while !stack.empty?
current = stack.last
left, right = current.left, current.right
if current.value == search_value
puts current
exit
elsif !left.nil? && !visited.include?(left)
if left.value == search_value
puts left
exit
else
visited << left
stack << left
end
elsif !right.nil? && !visited.include?(right)
if right.value == search_value
puts right
exit
else
visited << right
stack << right
end
else
stack.pop
end
end
puts "nil"
end
Calling the Methods
binary_tree = build_tree([4,7,2,8,1,1,1,30,22,4,9])
breadth_first_search(9, binary_tree)
depth_first_search(7, binary_tree)
visited
any use inbreadth_first_search()
? \$\endgroup\$