递归搜索嵌套列表并获取父级

时间:2014-04-22 12:12:47

标签: c# c#-4.0

我有一个班级:

public class Node
{
    public string name;
    public List<Node> children;

    public Node()
    {
        children = new List<Node>();
    }
}

我成功搜索并递归获取特定项目。我怎样才能得到父母?

public static Node Find(Node node, string name)
{

    if (node == null)
        return null;

    if (node.name == name)
        return node;

    foreach (var child in node.children)
    {
        var found = Find(child, name);
        if (found != null)
            return found;
    }

    return null;
}

3 个答案:

答案 0 :(得分:3)

如果您不想添加父节点以保持结构简单,您可以更改返回类型并返回节点和父节点。

class SearchResult {
 public Node Found;
 public Node Parent;
}

public static SearchResult Find(Node node, string name)
{

    if (node == null)
        return null;

    if (node.name == name)
        return new SearchResult { Found =  node, Parent = null};

    foreach (var child in node.children)
    {
        var found = Find(child, name);
        if (found != null)
                    return new SearchResult { Found =  found, Parent = node};
    }

    return null;
}

答案 1 :(得分:2)

简短的回答:你需要跟踪它。

例如:List<Node> children可以是一些自定义集合,如

public class Children : List<Node> {

    public Node Parent {get;set;}; 
    public Children(Node pr) {
        Parent = pr;
    }
}

所以:

  .....
  public Node()
  {
    children = new Children (this);
  }
  ...

或者,如果我正确地遵循你的逻辑:

    //node IS a parent of found node.
    foreach (var child in node.children)
    {
        var found = Find(child, name);
        if (found != null)
            return found;
    }

答案 2 :(得分:1)

最好的方法是在结构中保留对父级的引用。

如果您不想这样做,那么您可以稍微更改Find功能。像这样的东西(小心,它是在浏览器中写的)。

public static Tuple<Node, Node> Find(Node node, string name)
{
   return Find(node, name, null);
}

public static Tuple<Node, Node> Find(Node node, string name, Node parent)
{
    if (node == null)
        return null;

    if (node.name == name)
        return new Tuple<Node, Node>(node, parent);

    foreach (var child in node.children)
    {
        var found = Find(child, name, node);
        if (found != null)
            return found;
    }

    return null;
}