fork download
  1. // your code goes here
  2.  
  3. const list = new Map([ ['root', {nodeId: 'root', children: ['n1', 'n2']}], ['n2', {nodeId: 'n2', children: ['n3']}], ['n3', {nodeId: 'n3', children: ['n1', 'n4']}], ['n4', {nodeId: 'n4', children: []}] ]);
  4.  
  5. // console.log(JSON.stringify(list.get('root')));
  6.  
  7. const getRootSet = (rootNodeId, list) => {
  8. let results = [];
  9. let nodes = [rootNodeId];
  10. let index = 0;
  11. while(index < nodes.length) {
  12. const node = list.get(nodes[index]);
  13. // console.log('node'+index+': '+JSON.stringify(node));
  14. if(node) {
  15. results.push(node.nodeId);
  16. if (node.children.length > 0) {
  17. node.children.forEach(childId => {
  18. if(!nodes.includes(childId)) {
  19. nodes.push(childId);
  20. }
  21. });
  22. // console.log('nodes: '+JSON.stringify(nodes));
  23. }
  24. }
  25. index++;
  26. }
  27.  
  28. return results;
  29. };
  30.  
  31. // console.log(getRootSet('root', list));
  32. console.log(JSON.stringify(getRootSet('root', list)));
Success #stdin #stdout 0.03s 17480KB
stdin
Standard input is empty
stdout
["root","n2","n3","n4"]