c# - 如何在节点树中找到 NodeData?

标签 c# oop

我有一个如下所示的节点结构,这个节点有字符串数据和节点列表作为它的子节点。我想在这棵树中搜索数据 我写了一个递归函数 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/

相关文章:

oop - 模块化和面向对象编程之间的最大区别是什么?

java - 将数组从一个类调用到另一个类

c# - 带字符替换的字符串组合

c# - WPF 工具包饼图不显示

perl - 对象而不是 Perl 中的全局变量

c# - 构建通用应用程序 - 允许客户特定的选项

c# - 使用秒表对应用程序使用情况进行基准测试

c# 如果有新数据插入mysql则自动添加一个新按钮

C# 如何获取 2 个独立的类值节点并将它们写入数据表/dgv

c# - 使用 EPPlus 合并单元格?