2
* Definition for a binary tree node.3
* function TreeNode(val) {5
* this.left = this.right = null;10
* Encodes a tree to a single string.12
* @param {TreeNode} root15
var serialize = function (root) {16
// Using Preorder traversal to create a string of BST17
// Preorder works in following way18
// root -> left -> right22
if (node === null) return;24
preorder.push(node.val);26
// Get All the Left values29
// Get all the right values36
// Turn into string and return it37
return preorder.join(",");41
* Decodes your encoded data to tree.43
* @param {string} data46
var deserialize = function (data) {47
if (data === "") return null;49
// Get numbers array from a string50
const preorder = data.split(",").map(Number);52
// using -Infinity and +Infinity as placeholder check53
function recur(lower = -Infinity, upper = Infinity) {54
// This condition useful for when we are filling left side of tree it'll avoid all the values greater then then its upper value by putting null init.55
if (preorder[0] < lower || preorder[0] > upper) return null;57
// If preorder become empty58
if (preorder.length === 0) return null;60
// Create a root node [shift method will change the original array]61
const root = new TreeNode(preorder.shift());63
// Here for left side of tree, we are using current root node's value as 'upper bound' (so higher values ignored).64
root.left = recur(lower, root.val);66
// Same as above for right side we are using root node's values as 'lower bound' (so lower values ignored);67
root.right = recur(root.val, upper);72
// Final root will be out BST77
* Your functions will be called as such:78
* deserialize(serialize(root));