Skip to content

Instantly share code, notes, and snippets.

@albertywu
Last active May 26, 2020 04:55
Show Gist options
  • Select an option

  • Save albertywu/f4a5d33483ed0327422effda29e7b320 to your computer and use it in GitHub Desktop.

Select an option

Save albertywu/f4a5d33483ed0327422effda29e7b320 to your computer and use it in GitHub Desktop.
serialize / deserialize a binary tree
/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
var serialize = function(root) {
  let result = []
  
  // pre-order dfs
  function preorder(node) {
    if (node === null) {
      result.push(null)
      return
    }
    result.push(node.val)
    preorder(node.left)
    preorder(node.right)
  }
  preorder(root)
  return JSON.stringify(result)
};

/**
 * Decodes your encoded data to tree.
 *
 * @param {string} data
 * @return {TreeNode}
 */
var deserialize = function(dataStr) {
  const data = JSON.parse(dataStr)
  function build(data) {
    if (data[0] === null) {
      data.shift()
      return null
    }
    const root = new TreeNode(data[0])
    data.shift()
    root.left = build(data)
    root.right = build(data)
    return root
  }
  return build(data)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment