Last active
March 22, 2022 11:54
-
-
Save tgalopin/0bc9756776cb5faf5c676dc68ac56472 to your computer and use it in GitHub Desktop.
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
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