Skip to content

Instantly share code, notes, and snippets.

@mykeels
Created January 19, 2017 14:51
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 mykeels/3325f16d0a0ad4c920728951b81785ca to your computer and use it in GitHub Desktop.
Save mykeels/3325f16d0a0ad4c920728951b81785ca to your computer and use it in GitHub Desktop.
Breadth-First Search to get Tree Depth
//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));
@mykeels
Copy link
Author

mykeels commented Jan 19, 2017

getSampleTree and insertNodes are only used to generate a sample tree for test purposes ... please feel free to modify.

The getDepth(tree) code returns 3 when executed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment