Skip to content

Instantly share code, notes, and snippets.

@forrest-akin
Created October 10, 2020 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forrest-akin/62b1e75c0a0d702fdc35b15912e3d2fb to your computer and use it in GitHub Desktop.
Save forrest-akin/62b1e75c0a0d702fdc35b15912e3d2fb to your computer and use it in GitHub Desktop.
function serialize ( root ) {
const queue = root ? [ root ] : []
const nodes = []
while ( queue.length ) {
nodes.push( node = queue.shift() )
if ( node ) {
queue.push( node.left )
queue.push( node.right )
}
}
return nodes.map( node => node ? node.val : '' ).join( ',' )
}
function deserialize ( data ) {
const nodes = data.split( ',' ).map(value => value ? new TreeNode( Number( value ) ) : null )
const root = nodes.shift()
const queue = root ? [ root ] : []
while ( queue.length ) {
const node = queue.shift()
if ( node ) {
node.left = nodes.shift()
node.right = nodes.shift()
if ( nodes.length ) {
queue.push( node.left )
queue.push( node.right )
}
}
}
return root
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment