Skip to content

Instantly share code, notes, and snippets.

@catwell
Created November 29, 2022 13:53
Show Gist options
  • Save catwell/e964d56f981a87c5ff0e90547b2f6f74 to your computer and use it in GitHub Desktop.
Save catwell/e964d56f981a87c5ff0e90547b2f6f74 to your computer and use it in GitHub Desktop.
Binary tree serialization 😈
# Evil answer, don't try this at home 😈
def serialize(node, inbuf = nil)
buf = inbuf || StringIO.new
buf.write('Node.new(')
buf.write(node.val.inspect)
if node.left
buf.write(', ')
serialize(node.left, buf)
if node.right
buf.write(', ')
serialize(node.right, buf)
end
elsif node.right
buf.write(', nil, ')
serialize(node.right, buf)
end
buf.write(')')
buf.tap(&:rewind).read if inbuf.nil?
end
alias deserialize eval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment