Created
February 19, 2015 10:12
-
-
Save alexhawkins/d04a20e4e0b8fda592b2 to your computer and use it in GitHub Desktop.
How to find K Nodes at any level in a Binary Search Tree
This file contains hidden or 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
/*Once you get your data into a binary search tree, you can recurse it like below. | |
Use Depth First Traversal to keep track of the depth at each node in the tree. | |
On each recursive call, push the node at the current level to a hash table, using the | |
level as your key and the node as your value. | |
In JavaScript, you can use an array or an object literal to do this. I'm storing everything | |
in a JavaScript object literal which is similar to a hash table under the hood. Like this: | |
level = 0 | |
object[level] = [node1] => { '0': [node, node2] } | |
object[level] = [node2] => { '0': [node1, node2] } | |
level = 1 | |
object[level] = [node3] => { '0': [node, node2], '1': [node3] } | |
etc... | |
Before pushing, check to see if the key exists. If it doesn't exist, just insert the node into | |
your hash wrapped in an array. | |
If a key exists (meaning there is a level collision), invoke collision resolution by simply | |
pushing to the array at that key. | |
Now you have all the nodes at each level stored inside unique arrays inside an object. | |
It should look like this: | |
{ '0': [ 20 ], | |
'1': [ 8, 22 ], | |
'2': [ 4, 12, 24 ], | |
'3': [ 10, 14 ] } | |
Or this if you're storing the entire node: | |
{ '0': [ { value: 20, right: [Object], left: [Object] } ], | |
'1': | |
[ { value: 8, right: [Object], left: [Object] }, | |
{ value: 22, right: [Object], left: null } ], | |
'2': | |
[ { value: 4, right: null, left: null }, | |
{ value: 12, right: [Object], left: [Object] }, | |
{ value: 24, right: null, left: null } ], | |
'3': | |
[ { value: 10, right: null, left: null }, | |
{ value: 14, right: null, left: null } ] } | |
You can do what you want with them after this. | |
-Sum the values at each level | |
-convert to a linked list | |
-just check the length of the array at the desired level. This will give you the number of nodes. | |
*/ | |
BinaryTree.prototype.kNodesAtDepth = function(level) { | |
var levels = {}; | |
var traverse = function(current, depth) { | |
if (!current) return null; | |
if (!levels[depth]) levels[depth] = [current.value]; | |
else levels[depth].push(current.value); | |
traverse(current.left, depth + 1); | |
traverse(current.right, depth + 1); | |
}; | |
traverse(this.root, 0); | |
return levels[level].length; | |
}; | |
//tests | |
var bst = new BinaryTree(); | |
bst.add(20, 22, 8, 4, 12, 10, 14, 24); | |
var nodeCount = bst.kNodesAtDepth(2); //3 | |
console.log(nodeCount); //3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment