2016-02-08 51 views
1

我正在嘗試實現n-ary樹的搜索算法。以下是我寫的代碼: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; } 
} 

我需要做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即使元素的子樹中存在。這是因爲最後的回報錯誤。如果我刪除它,比我得到一個編譯器錯誤,說所有的代碼路徑必須返回一個值。

一旦在樹中找到元素,我該如何停止遞歸?

回答

4

如果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; 

}

+0

感謝那些幫助:) –