Last active
August 29, 2015 14:01
-
-
Save kyledcline/415b2b133a8c1bc3fbd2 to your computer and use it in GitHub Desktop.
Simple binary search tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BinarySearchTree | |
Node = Struct.new(:key, :left, :right) | |
attr_reader :root | |
def initialize(root=nil, *keys) | |
@root = Node.new(root) | |
build_tree(*keys) unless keys.empty? | |
end | |
def ordered_keys | |
@ordered_keys = [] | |
traverse | |
@ordered_keys | |
end | |
def find(value) | |
node = root | |
until node.nil? | |
if node.key > value | |
node = node.left | |
elsif node.key < value | |
node = node.right | |
elsif node.key == value | |
return true | |
end | |
end | |
false | |
end | |
private | |
def build_tree(*key_values) | |
key_values.each { |key| insert_node(key) } | |
end | |
def insert_node(value) | |
node = root | |
until node.nil? | |
if node.key > value && node.left | |
node = node.left | |
elsif node.key < value && node.right | |
node = node.right | |
elsif node.key > value | |
node.left = Node.new(value) | |
return value | |
elsif node.key < value | |
node.right = Node.new(value) | |
return value | |
elsif node.key == value | |
return value | |
end | |
end | |
end | |
def add_key(node_key) | |
@ordered_keys << node_key | |
end | |
def traverse(node=@root) | |
return if node.nil? | |
traverse(node.left) | |
add_key(node.key) | |
traverse(node.right) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code kata to create and search a binary tree of integers.
Example usage