JS DFS/Recursive solution 420ms+


  • 0
    C

    here is my solution.

    /**
     * @param {number[]} pid
     * @param {number[]} ppid
     * @param {number} kill
     * @return {number[]}
     */
    var killProcess = function(pid, ppid, kill) {
      var idHash = {};
      // build a parent - children table
      for (var i = ppid.length - 1; i >= 0; i--) {
        if(idHash[ppid[i]]){
          idHash[ppid[i]].push(pid[i]);
        } else {
          idHash[ppid[i]] = [pid[i]];
        }
      }
      // console.log(idHash);
      var res = [kill];
      findChildren(idHash,kill);
    
      function findChildren(idHash, killId) {
        // console.log("res " + res +" kill: " + killId);
        if(!idHash[killId]) return res; // leaf Node
        res = [].concat.call(res,idHash[killId]);
        // console.log("found " + res);
        for (var i = idHash[killId].length - 1; i >= 0; i--) {
          findChildren(idHash, idHash[killId][i],res);
        }
      }
    
      return res;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.