Leetcode 690: Employee Importance Solution

Here is another LeetCode solution for Employee Importance Problem.

/**
* Definition for Employee.
* class Employee {
*     public $id = null;
*     public $importance = null;
*     public $subordinates = array();
*     function __construct($id, $importance, $subordinates) {
*         $this->id = $id;
*         $this->importance = $importance;
*         $this->subordinates = $subordinates;
*     }
* }
*/

class Solution {
/**
 * @param Employee[] $employees
 * @param Integer $id
 * @return Integer
 */

function getImportance($employees, $id) {
  if (empty($employees)) return 0;
  $emap = [];
  foreach ($employees as $e) {
    $emap[$e->id] = $e;
  }

  return $this->recurse($emap, $id);
 }

function recurse($emap, $id) {
  $e = $emap[$id];
  $ans = $e->importance;
  foreach ($e->subordinates as $sub) {
    $ans += $this->recurse($emap, $sub);
  }
  return $ans;
 }
}
Published on

Previous post: LeetCode 1249. Minimum Remove to Make Valid Parentheses

Next post: LeetCode 844. Backspace String Compare