Created
January 16, 2018 08:48
-
-
Save alexspark/d8aee8c82f275b73ca98da10b20f2ca0 to your computer and use it in GitHub Desktop.
Level-order traversal of a binary tree
This file contains hidden or 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 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