Skip to content

Instantly share code, notes, and snippets.

@adamthedeveloper
Last active December 20, 2015 02:49
Show Gist options
  • Save adamthedeveloper/6059519 to your computer and use it in GitHub Desktop.
Save adamthedeveloper/6059519 to your computer and use it in GitHub Desktop.
Rebuild a binary tree from an array.
class Node
attr_accessor :data, :left, :right
def initialize(*args)
@data,@left,@right = args
end
end
class Tree
attr_accessor :root
def initialize
@root = Node.new
end
def insert(val, node=nil)
@root = Node.new(val) and return if @root.nil? or @root.data.nil?
node ||= @root # Start with the root node if one wasn't passed
return if val == node.data
if val < node.data
node.left = Node.new(val) and return if node.left.nil?
recur_node = node.left
else
node.right = Node.new(val) and return if node.right.nil?
recur_node = node.right
end
self.insert(val, recur_node)
end
def to_array
q, arr = [root], []
while !q.empty?
node = q.shift
arr << node.data
q << node.left unless node.left.nil?
q << node.right unless node.right.nil?
end
arr
end
end
tree = Tree.new
[3, 2, 1, 2.25, 4, 9, 7, 10, 23, 77].each do |val|
tree.insert val
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment