Created
October 10, 2020 22:27
-
-
Save forrest-akin/62b1e75c0a0d702fdc35b15912e3d2fb 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
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