Skip to content

Instantly share code, notes, and snippets.

@ch1c0t
Last active March 9, 2017 00:55
Show Gist options
  • Save ch1c0t/ddf16e3a9db5cb3579eea0dc77fb6541 to your computer and use it in GitHub Desktop.
Save ch1c0t/ddf16e3a9db5cb3579eea0dc77fb6541 to your computer and use it in GitHub Desktop.
# http://eli.thegreenplace.net/2011/09/29/an-interesting-tree-serialization-algorithm-from-dwarf
def load array
root = Node.new array.shift.first
stack = [root]
array.each do |pair|
if pair.nil?
stack.pop
else
node = Node.new pair.first
stack.last.add_child node
stack.push node if pair.last
end
end
root
end
def dump root
array = []
serialize = -> node do
if node.children.empty?
array.push [node.value, false]
else
array.push [node.value, true]
node.children.each { |node| serialize[node] }
array.push nil
end
end
serialize[root]
array
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment