Skip to content

Instantly share code, notes, and snippets.

@sanchojaf
Last active November 6, 2016 16:42
Show Gist options
  • Save sanchojaf/6fd7aa50ab96135da74cb4599ef1e154 to your computer and use it in GitHub Desktop.
Save sanchojaf/6fd7aa50ab96135da74cb4599ef1e154 to your computer and use it in GitHub Desktop.
Breadth-First Insertion and Traversal in a Binary Tree
# The traverse iterator will iterate over the tree in the same
# breadth-first order.
class Tree
attr_accessor :left
attr_accessor :right
attr_accessor :data
def initialize(x=nil)
@left = @right = nil
@data = x
end
def insert(x)
list = []
if @data.nil?
@data = x
elsif @left.nil?
@left = Tree.new x
elsif @right.nil?
@right = Tree.new x
else
list << @left << @right
loop do
node = list.shift
node.insert(x) and break if node.left.nil?
list << node.left
node.insert(x) and break if node.right.nil?
list << node.right
end
end
end
end
def traverse
list = []
yield @data
list << @left unless @left.nil?
list << @right unless @right.nil?
until list.empty?
node = list.shift
yield node.data
list << node.left unless node.left.nil?
list << node.right unless node.right.nil?
end
end
items = (1..7).to_a
tree = Tree.new
items.each { |x| tree.insert x }
tree.traverse { |x| print "#{x} " }
puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment