Skip to content

Instantly share code, notes, and snippets.

@woonketwong
Created January 13, 2014 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woonketwong/8394106 to your computer and use it in GitHub Desktop.
Save woonketwong/8394106 to your computer and use it in GitHub Desktop.
Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists)
var findLevelLinkedList = function(root){
var queue = [];
var linkedListArray = [];
var level = 0;
queue.push([root, level]);
root.visit = true;
while(queue.length !== 0){
var tempObj = queue.pop();
var currentNode = tempObj[0];
level = tempObj[1];
if (linkedListArray[level] === undefined){
linkedList = makeLinkedList(currentNode);
linkedListArray[level] = linkedList;
} else{
linkedList = linkedListArray[level];
linkedList.add(currentNode);
}
for (var i = 0; i < currentNode.next.length; i++){
if(currentNode.next[i].visit !== true){
queue.push([currentNode.next[i], level+1]);
currentNode.next[i].visit = true;
}
}
}
return linkedListArray;
};
var makeLinkedList = function(node){
var root = {};
var currentNode = {};
var makeNode = function(value){
var obj = {
value: value,
next: null
}
return obj;
};
root = makeNode(node.value);
currentNode = root;
var linkedList = {
add: function(node){
currentNode.next = makeNode(node.value);
currentNode = currentNode.next;
},
getRoot: function(){
return root;
}
};
return linkedList;
};
// var makeNode = function(key, value){
// var obj = {"key": key,
// "value": value,
// "next": [],
// visit: false};
// return obj;
// }
// tree
// 1
// |
// 2 3
// | |
// 4 5 6 7
// var root = makeNode("1", "apple");
// var node1 = makeNode("2", "orange");
// var node2 = makeNode("3", "kiwi");
// root.next.push(node1);
// root.next.push(node2);
// var node1 = makeNode("4", "banana");
// var node2 = makeNode("5", "blueberry");
// root.next[0].next.push(node1);
// root.next[0].next.push(node2);
// var node1 = makeNode("6", "grape");
// var node2 = makeNode("7", "pineapple");
// root.next[1].next.push(node1);
// root.next[1].next.push(node2);
// var result = findLevelLinkedList(root);
// for (var i = 0; i < result.length; i++){
// console.log(result[i].getRoot().value, result[i].getRoot().next);
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment