Created
November 29, 2022 13:53
-
-
Save catwell/e964d56f981a87c5ff0e90547b2f6f74 to your computer and use it in GitHub Desktop.
Binary tree serialization π
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
# 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