组织架构遍历算法
1、递归算法
function get_all_subordinates($root_id) {
$result = [];
$subordinates = Db::name('employee')->whereIn('pid', $root_id)->select();
foreach ($subordinates as $subordinate) {
$result[] = $subordinate['name'];
$sub_result = get_all_subordinates([$subordinate['id']]);
$result = array_merge($result, $sub_result);
}
return $result;
}
// 测试代码
$root_id = [1]; // 传入根节点的ID
$result = get_all_subordinates($root_id);
print_r($result);
空间复杂度:F(n)
时间复杂度:O(n2),最坏的情况
2、遍历循环算法
function get_all_subordinates($root_id) {
$result = [];
// 使用循环依次查询每一级的下级员工
while (true) {
$subordinates = Db::name('employee')->whereIn('pid', $root_id)->select();
if (empty($subordinates)) {
break;
}
$result = array_merge($result, array_column($subordinates, 'name'));
$root_id = array_column($subordinates, 'id');
}
return $result;
}
// 测试代码
$root_id = [1]; // 传入根节点的ID
$result = get_all_subordinates($root_id);
print_r($result);
空间复杂度:F(1)
时间复杂度:O(n),最坏的情况

本文介绍了两种在数据库中遍历组织架构获取所有子级员工的方法,分别是递归算法和循环算法。递归算法虽然空间复杂度较高(F(n)),但时间复杂度为O(n^2),而循环算法的空间复杂度较低(F(1)),时间复杂度为O(n)。
8126

被折叠的 条评论
为什么被折叠?



