Skip to content

Instantly share code, notes, and snippets.

@tgalopin
Last active March 22, 2022 11:54
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 tgalopin/0bc9756776cb5faf5c676dc68ac56472 to your computer and use it in GitHub Desktop.
Save tgalopin/0bc9756776cb5faf5c676dc68ac56472 to your computer and use it in GitHub Desktop.
const forest = [/* ... */];
let forestKey = 0;
let childKey = 0;
let isChild = {};
// O(n) loop
while (true) {
// O(1) : access by key to a hash map
if (typeof forest[forestKey] === 'undefined') {
break;
}
// O(1) + O(1) : access by key to a hash map
if (typeof forest[forestKey].children[childKey] === 'undefined') {
++forestKey;
childKey = 0;
continue;
}
++childKey;
// O(1) : set by key of a hash map
isChild[forest[forestKey].children[childKey]] = true;
}
let rootNodes = [];
// O(n) loop
for (let i in forest) {
// O(1) : access by key to a hash map
if (typeof isChild[forest[i]] === 'undefined') {
rootNodes.push(forest[i]);
}
}
return rootNodes;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment