Created
July 24, 2019 15:51
-
-
Save wataruoguchi/90a084c8ab0b76b0ee3130f286d049e5 to your computer and use it in GitHub Desktop.
Binary Tree in JS : https://www.youtube.com/watch?v=suj1ro8TIVY
This file contains hidden or 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) { | |
if (!root) { | |
return 'X,' | |
} | |
const left = serialize(root.left); | |
const right = serialize(root.right); | |
return root.val += `,${left}${right}`; | |
} | |
function deserialize(str) { | |
const nodesLeft = str.split(','); | |
return deserializeHelper(nodesLeft); | |
} | |
function deserializeHelper(nodesLeft) { | |
const val = nodesLeft.shift(); | |
console.log(val); | |
if (val === 'X') return null; | |
return { | |
val, | |
left: deserializeHelper(nodesLeft), | |
right: deserializeHelper(nodesLeft), | |
}; | |
} | |
const seed = "1,2,X,X,3,4,X,X,5,X,X,"; | |
const des = deserialize(seed); | |
console.log(des); | |
const ser = serialize(des); | |
console.log('assert', seed === ser); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment