n-ary树中的搜索算法

Aru*_*mar 1 c# algorithm tree

我正在尝试为n-ary树实现搜索算法.以下是我写的代码:

public class Employee
{

    public int EmployeeId { get; set; }
    public string Level { get; set; }
    public int BillCode { get; set; }

    public virtual List<Employee> ReportsTo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我需要在树上执行BFS以查找子节点中的元素,并在树中找到元素时停止递归.我到目前为止写的代码是:

static bool ClosestManager(Employee a, Employee b) //a contains all the tree elements and b is the one that I need to find
    {
      if (a.EmployeeId == b.EmployeeId)
            return true;
        if (a.ReportsTo != null)
        {
            foreach (var curremployee in a.ReportsTo)
            {
                ClosestManager(curremployee, b);
            }
        }
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

即使元素存在于子树中,也始终返回false.这是因为最终的回报是假的.如果我删除它比我得到编译器错误说所有代码路径必须返回一个值.

一旦在树中找到元素,我该如何停止递归?

Adi*_*vin 5

如果在递归调用中找到ClosestManager,则返回true:

static bool ClosestManager(Employee a, Employee b) //a contains all the tree elements and b is the one that I need to find
{
  if (a.EmployeeId == b.EmployeeId)
    return true;
  if (a.ReportsTo != null)
  {
    foreach (var curremployee in a.ReportsTo)
    {
      if (ClosestManager(curremployee, b))
         return true;
    }
  }
  return false;
Run Code Online (Sandbox Code Playgroud)

}