Skip to content

Instantly share code, notes, and snippets.

@rchasman
Created April 29, 2014 00:14
Show Gist options
  • Save rchasman/11387713 to your computer and use it in GitHub Desktop.
Save rchasman/11387713 to your computer and use it in GitHub Desktop.
Deserialize/Serialize a Binary Tree structure from/into a String.
/** SIG FIG INTERVIEW **/
var node = function(value, left, right) {
this.value = value;
this.left = left;
this.right = right;
};
/**
n - current node
2n+1 - left child
2n+2 - right child
**/
var deserializeTree = function(data, index) {
if(index <= data.length && data[index] !== '*') {
var tree = new node(undefined);
tree.value = data[index];
tree.left = deserializeTree(data, 2 * index + 1);
tree.right = deserializeTree(data, 2 * index + 2);
return tree;
}
};
/**
5
| |
10 2
| | | |
2 4
**/
var data = "5/10/2/2/*/4/*".split("/");
console.log(data);
console.log(deserializeTree(data, 0));
/**
My .vimrc:
https://github.com/rchasman/dotfiles/blob/master/.vimrc
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment