我正在尝试为n-ary树实现搜索算法。以下是我写的代码:
Sub copyRange()
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Range("L2:S7").Select
ActiveSheet.Paste
Range("A3").Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.Copy
Range("L8:S13").Select
ActiveSheet.Paste
Range("A4").Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.Copy
Range("L14:S19").Select
ActiveSheet.Paste
Range("A5").Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.Copy
ActiveWindow.SmallScroll Down:=3
Range("L20:S25").Select
ActiveSheet.Paste
End Sub
我需要在树上执行BFS以查找子节点中的元素,并在树中找到元素时停止递归。 我到目前为止写的代码是:
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; }
}
即使元素存在于子树中,也始终返回false。这是因为最终的回报是假的。如果我删除它比我得到编译器错误说所有代码路径必须返回一个值。
如果在树中找到元素,我该如何停止递归?
答案 0 :(得分: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;
}