我正在尝试实现n元树的搜索算法。下面是我写的代码:

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

我需要在树上执行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;
    }

这个元素总是返回false,即使元素存在于子树中。这是因为最终的返回错误如果删除它,编译器会错误地指出所有代码路径都必须返回一个值。
如何在树中找到元素后停止递归?

最佳答案

如果在递归调用中找到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;

}

09-30 14:06
查看更多