Recursively search for nested lists and get parent

I have a class:

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

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

I successfully perform a search and recursively get a specific item. How can I get a parent?

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;
}
+4
source share
3 answers

If you do not want to add a parent node to simplify the structure, you can change the type of the return value and return both the node and the parent.

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;
}
+3
source

Short answer: you need to follow him.

for example: there List<Node> childrenmay be some kind of custom collection, for example

public class Children : List<Node> {

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

So:

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

Or if I follow your logic correctly:

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

- .

, 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;
}
+1

Source: https://habr.com/ru/post/1537503/


All Articles