n叉树中的搜索算法
Search algorithm in n-ary tree
我正在尝试实现 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;
}
这个总是 returns false 即使该元素存在于子树中。这是因为最后 return false。如果我删除它比我得到一个编译器错误说所有代码路径必须 return 一个值。
在树中找到元素后如何停止递归?
如果在递归调用中找到 ClosestManager,则 return 为真:
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;
}
我正在尝试实现 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;
}
这个总是 returns false 即使该元素存在于子树中。这是因为最后 return false。如果我删除它比我得到一个编译器错误说所有代码路径必须 return 一个值。
在树中找到元素后如何停止递归?
如果在递归调用中找到 ClosestManager,则 return 为真:
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;
}