Skip to content

Instantly share code, notes, and snippets.

@stephnr
Created April 1, 2016 15:36
Show Gist options
  • Save stephnr/6f1e347b824fa9cc2d7de72096629a16 to your computer and use it in GitHub Desktop.
Save stephnr/6f1e347b824fa9cc2d7de72096629a16 to your computer and use it in GitHub Desktop.
// Built from https://github.com/zhiyelee/node-leetcode
/**
* Converts an array into a Linked List
* @param {Array<Number>} arr the array to convert
* @return {Object} the linked list object
*/
var createList = arr => {
var head = { val: null, next: null };
var current = head;
arr.forEach(el => {
current.next = { val: el, next: null };
current = current.next;
});
return head.next;
}
/**
* Converts an array into a Binary Tree
* @param {Array<Number>} arr the array to convert
* @return {Object} the binary tree object
*/
var createTree = arr => {
// 1. check for an empty tree
if(!arr.length || arr[0] === null) return null;
var len = arr.length;
// 2. setup the root node
var root = { val: arr[0], left: null, right: null };
// 3. track remaining nodes
var nodes = arr.slice(1);
// 4. track remaining children for continuing tree traversal
var children = [root];
// 5. track current tree step
var current = root;
// 6. loop through remaining children (starting at root node)
while(children.length) {
// 7. grab the first child
current = children.shift();
// 8. verify we received a valid node
if(!current || current.val === null) {
continue;
}
// 9. check for left node
if(nodes.length) {
current.left = { val: nodes.shift(), left: null, right: null };
children.push(current.left);
}
// 10. check for right node
if(nodes.length) {
current.right = { val: nodes.shift(), left: null, right: null };
children.push(current.right);
}
}
// 11. return the new node tree
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment