简体   繁体   English

n元树中的搜索算法

[英]Search algorithm in n-ary tree

I am trying to implement search algorithm for n-ary tree. 我正在尝试为n元树实现搜索算法。 Following is the code that I have written: 以下是我编写的代码:

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

I need to do BFS on the tree to find the element in the child nodes and to stop the recursion when the element is found in the tree. 我需要在树上执行BFS,以在子节点中找到元素,并在树中找到该元素时停止递归。 The code that I wrote so far is: 到目前为止,我编写的代码是:

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

This one always returns false even if the element exists in the subtree. 即使该元素存在于子树中,此元素也始终返回false。 It is because of the return false in the end. 最终是因为返回false。 If I remove it than I get a compiler error saying that all code path must return a value. 如果删除它,则会收到编译器错误,提示所有代码路径必须返回一个值。

How do I stop recursion once the element is found in the tree ? 在树中找到元素后,如何停止递归?

Just return true if a ClosestManager is found in the recursive call: 如果在递归调用中找到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;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM