Skip to content

Instantly share code, notes, and snippets.

@sghiassy
Created June 17, 2017 19:43
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 sghiassy/5a74f8c2436f388d31b91515652b1582 to your computer and use it in GitHub Desktop.
Save sghiassy/5a74f8c2436f388d31b91515652b1582 to your computer and use it in GitHub Desktop.
class Node {
constructor(value = "", parent = undefined) {
this.value = value;
this.parent = parent;
this.children = [];
if (this.parent != undefined) {
this.parent.children.push(this);
}
}
description() {
return this.value;
}
}
const root = new Node(1);
const two = new Node(2, root);
const three = new Node(3, root);
const four = new Node(4, two);
const five = new Node(5, two);
const six = new Node(6, three);
const seven = new Node(7, three);
const eight = new Node(8, four);
const nine = new Node(9, five);
const ten = new Node(10, seven);
const eleven = new Node(11, eight);
let lowestValue = undefined;
function findMinDepth(node, currentDepth = 1) {
const reachedLeafNode = node.children.length == 0;
if (reachedLeafNode) {
if (lowestValue === undefined || currentDepth < lowestValue) {
lowestValue = currentDepth;
}
return;
}
node.children.forEach((childNode, i) => {
findMinDepth(childNode, currentDepth + 1);
});
}
findMinDepth(root);
console.log(`Minimum Depth is ${lowestValue}`)
// OUTPUT
// Minimum Depth is 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment