遍历树时查找节点

Ton*_*Nam 7 c# linq tree data-structures

我想实现一个方法,使我能够在树中找到一个节点.我这样做的方式是递归使用全局变量来知道何时停止.

我上课了:

class Node    // represents a node in the tree
{ 
     // constructor
     public Node() {
          Children = new List<Node>();
     }

     public List<Node> Children; 
     public string Name;
     public string Content;            
}
Run Code Online (Sandbox Code Playgroud)

我现在的方法是:

    private bool IsNodeFound = false; // global variable that I use to decide when to stop

    // method to find a particular node in the tree
    private void Find(Node node, string stringToFind, Action<Node> foundNode)
    {
        if(IsNodeFound)
           return;

        if (node.Content.Contains(stringToFind)){
            foundNode(node); 
            IsNodeFound =true;               
        }

        foreach (var child in node.Children)
        {
            if (child.Content.Contains(stringToFind)){
                foundNode(node);
                IsNodeFound =true;               
            }

            Find(child, stringToFind, foundNode);
        }

    }
Run Code Online (Sandbox Code Playgroud)

以及我使用Find方法的方式如下:

   // root is a node that contain children and those children also contain children
   // root is the "root" of the tree
   IsNodeFound =false;
   Node nodeToFind = null;
   Find(root, "some string to look for", (x)=> nodeToFind=x);
Run Code Online (Sandbox Code Playgroud)

所以我的问题是如何让这种方法更优雅.我希望方法的签名看起来像:

   public Node FindNode(Node rootNode);
Run Code Online (Sandbox Code Playgroud)

我认为这是多余的我在做什么,并且可能有更好的方法来创建该方法.或许我可以改变Node类,以便我可以使用linq查询实现相同的功能.

Ani*_*Ani 13

我会这样做:

编写实例方法以生成节点的子树(如果不控制Node该类,可以将其作为扩展):

public IEnumerable<Node> GetNodeAndDescendants() // Note that this method is lazy
{
     return new[] { this }
            .Concat(Children.SelectMany(child => child.GetNodeAndDescendants()));    
}
Run Code Online (Sandbox Code Playgroud)

然后你可以找到一些LINQ的节点:

var foundNode = rootNode.GetNodeAndDescendants()
                        .FirstOrDefault(node => node.Content.Contains(stringToFind));

if(foundNode != null)
{
    DoSomething(foundNode);
}
Run Code Online (Sandbox Code Playgroud)


Rya*_*yan 13

您可以使用使用Linq的其他答案之一,也可以使用递归的深度优先搜索机制:

public Node Find(string stringToFind)
{
    // find the string, starting with the current instance
    return Find(this, stringToFind);
}

// Search for a string in the specified node and all of its children
public Node Find(Node node, string stringToFind)
{
    if (node.Content.Contains(stringToFind))
        return node;

    foreach (var child in node.Children) 
    { 
        var result = Find(child, stringToFind);
        if (result != null)
            return result;
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)