Created
January 19, 2017 14:51
-
-
Save mykeels/3325f16d0a0ad4c920728951b81785ca to your computer and use it in GitHub Desktop.
Breadth-First Search to get Tree Depth
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
//pseudocode | |
function Node() { | |
this.children = []; | |
var me = this; | |
this.hasChildren = function () { | |
return me.children.length > 0; | |
} | |
} | |
function getDepth(node, count, max) { | |
count = count || 0; | |
max = max || 0; | |
if (node.hasChildren()) { | |
count++; | |
max = Math.max(max, count); | |
for (var i = 0; i < node.children.length; i++) { | |
return getDepth(node.children[i], count, max); | |
} | |
} | |
else { | |
max = Math.max(max, count); | |
} | |
return ++max; | |
} | |
function insertNodes(node, count) { | |
count = count || 3; | |
node = node || new Node(); | |
for (var i = 0; i < count; i++) { | |
node.children.push(new Node()); | |
} | |
return node; | |
} | |
function getSampleTree() { | |
var root = new Node(); | |
root = insertNodes(root); | |
root.children[0] = insertNodes(root.children[0]);//adds extra depth | |
return root; | |
} | |
var tree = getSampleTree(); | |
console.log(getDepth(tree)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
getSampleTree
andinsertNodes
are only used to generate a sample tree for test purposes ... please feel free to modify.The
getDepth(tree)
code returns 3 when executed