Skip to content

Instantly share code, notes, and snippets.

@Supernats
Last active August 29, 2015 14:00
Show Gist options
  • Save Supernats/11391827 to your computer and use it in GitHub Desktop.
Save Supernats/11391827 to your computer and use it in GitHub Desktop.
class TreeNode
attr_accessor :left, :right, :value
def initialize(value)
@value = value
end
# to be called on parent
# for full tree
def print
flat = self.flatten
Integer(Math.log2(flat.length + 1)).times do |i|
row = flat.shift(2 ** i)
puts row.to_s
end
end
def flatten
flat = [self]
flat.each do |node|
flat << node.left if node.left
flat << node.right if node.right
end
flat
end
def to_s
self.value
end
end
a = TreeNode.new("a")
b = TreeNode.new("b")
c = TreeNode.new("c")
d = TreeNode.new("d")
e = TreeNode.new("e")
f = TreeNode.new("f")
g = TreeNode.new("g")
a.left, a.right = b, c
b.left, b.right = d, e
c.left, c.right = f, g
d.left, d.right = nil, nil
e.left, e.right = nil, nil
f.left, f.right = nil, nil
g.left, g.right = nil, nil
a.print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment