Skip to content

Instantly share code, notes, and snippets.

@alexspark
Created January 16, 2018 08:48
Show Gist options
  • Save alexspark/d8aee8c82f275b73ca98da10b20f2ca0 to your computer and use it in GitHub Desktop.
Save alexspark/d8aee8c82f275b73ca98da10b20f2ca0 to your computer and use it in GitHub Desktop.
Level-order traversal of a binary tree
class Node
attr_accessor :value, :left, :right
def initialize(value)
@value = value
end
end
def level_order_traversal(node)
queue = [node]
loop do
nxt = queue.shift
puts nxt.value
queue.push nxt.left if nxt.left
queue.push nxt.right if nxt.right
break if queue.empty?
end
end
a = Node.new(1)
a.left = Node.new(2)
a.left.left = Node.new(3)
a.left.right = Node.new(4)
a.right = Node.new(5)
level_order_traversal(a) # 1, 2, 5, 3, 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment