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;
}
}