Last active
August 29, 2015 14:20
-
-
Save itrelease/825a20920591fab522d7 to your computer and use it in GitHub Desktop.
pack-unpack
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) { | |
if (root == null) | |
return "- "; | |
else { | |
return root.value + " " + serialize(root.node.left) + serialize(root.node.right); | |
} | |
} | |
function deserialize(string) { | |
var tokens = string.trim().split(' '); | |
var index = { | |
value: 0 | |
}; | |
return _deserialize(tokens, index); | |
} | |
function _deserialize(arr, index) { | |
if (index.value >= arr.length) | |
return null; | |
if (arr[index.value] === '-') { | |
index.value += 1; | |
return null; | |
} | |
var value = parseInt(arr[index.value], 10); | |
console.log('VALUE:', value); | |
var tree = new Node(value); | |
index.value += 1; | |
tree.node.left = _deserialize(arr, index); | |
tree.node.right = _deserialize(arr, index); | |
return tree; | |
} | |
function Node(value, left, right) { | |
this.value = value; | |
this.node = {}; | |
if (left) { | |
this.node.left = left; | |
} | |
if (right) { | |
this.node.right = right; | |
} | |
} | |
var tree = new Node(1); | |
var tLeft = new Node(2); | |
var tRight = new Node(3); | |
tree.node.left = tLeft; | |
tree.node.right = tRight; | |
var tSerialized = serialize(tree); | |
console.log('SERIALIZED: ', tSerialized); | |
deserialize(tSerialized); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment