Skip to content

Instantly share code, notes, and snippets.

@amckemie
Created May 29, 2014 00:59
Show Gist options
  • Save amckemie/f5aa395a9a66cc405bfb to your computer and use it in GitHub Desktop.
Save amckemie/f5aa395a9a66cc405bfb to your computer and use it in GitHub Desktop.
Binary_Search_Tree
class Node
attr_accessor :left_child, :right_child
attr_reader :value
def initialize(value)
@value = value
@left_child = nil
@right_child = nil
end
end
class Tree
attr_reader :head
def build_tree(array)
mid_point = array[array.length/2]
@head = Node.new(mid_point)
left = array[0...array.length/2]
right = array[(array.length/2 + 1)..-1]
if left.length > 0
@head.left_child = _build_tree(left)
end
if right.length > 0
@head.right_child = _build_tree(right)
end
end
def _build_tree(array)
if array.length != 1
mid_point = array[array.length/2]
left = array[0...array.length/2]
right = array[(array.length/2 + 1)..-1]
node = Node.new(mid_point)
if left.length > 0
node.left_child = _build_tree(left)
end
if right.length > 0
node.right_child = _build_tree(right)
end
return node
else
return Node.new(array[0])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment