Last active
March 9, 2017 00:55
-
-
Save ch1c0t/ddf16e3a9db5cb3579eea0dc77fb6541 to your computer and use it in GitHub Desktop.
This file contains 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
# 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