我希望能够实现一种方法,使我能够在树中查找节点。我的做法是通过递归使用全局变量来知道何时停止。
我有以下类:
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;
}
目前我拥有的方法是:
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);
}
}
我使用的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);
所以我的问题是如何让这个方法更优雅。我希望该方法的签名看起来像:
public Node FindNode(Node rootNode);
我认为我的做法过于冗余,可能有更好的方法来创建这个方法。或者我可以修改 Node 类,以便通过 linq 查询实现相同的效果。
root.GetSubTree().FirstOrDefault(x => x.Name=="Foo");
非常感谢! - Tono Nam