我有一个如下所示的节点结构,这个节点有字符串数据和节点列表作为它的子节点。我想在这棵树中搜索数据 我写了一个递归函数 FindNode(Node intree,string target)
public class Node
{
public string Data;
public List<Node> Children = new List<Node>();
//some code
public Node(string r)
{
this.Data = r;
}
public string getData()
{
return this.Data;
}
//some code
public List<Node> getchildren()
{
return this.Children;
}
//some code
}
target 是我要查找的字符串,intree 是树的开始(ROOT) 我在 while 循环后遇到问题在那之后我应该返回什么? 如果我写错了应该怎么写?
public Node FindNode(Node intree,string target)
{
if(intree.getData()==target)
return intree;
else
{
while(intree.getchildren()!=null)
{
foreach(Node n in intree.getchildren())
{
FindNode(n,target);
}
}
}
}
最佳答案
使用这个:
public Node FindNode(Node intree,string target)
{
if(intree.getData()==target)
return intree;
else
{
foreach(Node n in intree.getchildren())
{
Node node = FindNode(n,target) ; //CHECK FOR RETURN
if(node != null)
return node;
}
}
return null;
}
区别是我检查了FindNode
方法的返回值,如果不是null
,返回结果。
请注意,如果树中存在重复节点(具有相同字符串的节点),它将返回第一次出现。
关于c# - 如何在节点树中找到 NodeData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10241487/