Skip to content

Instantly share code, notes, and snippets.

@MauriRojas
Last active May 21, 2018 19:41
Show Gist options
  • Save MauriRojas/d5693e37f6b974623c22650353a4cf52 to your computer and use it in GitHub Desktop.
Save MauriRojas/d5693e37f6b974623c22650353a4cf52 to your computer and use it in GitHub Desktop.
Serialize and deserialize binary trees with JavaScript
('use strict');
function Node(val, left, right) {
this.val = val;
this.left = left;
this.right = right;
}
function deserialize(nodeString) {
var splited = nodeString.split(",");
var index = 0;
function encode(splited) {
if (index == splited.lenght || splited[index] == '#') {
index++;
return null;
}
var root = new Node(splited[index], null, null);
index++;
root.left = encode(splited);
root.right = encode(splited);
return root;
}
return encode(splited);
}
function serialize(root) {
var serial = "";
function decode(node) {
if (node == null) {
serial += "#,";
} else {
serial += node.val + ",";
decode(node.left);
decode(node.right);
}
}
decode(root);
return serial;
}
module.exports = {Node, serialize, deserialize};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment