Java:我的通用树遍历实现有什么不正确的地方?

Java: What's incorrect with my general tree traversal implementation?

我的任务是从字符串 targetName 给出的一般树中查找并 returning 一个特定节点。看看下面我的实现:

public GeneralTreeNode findNode(String targetName) {          
    if (this.name.equals(targetName)) {
        return this;
    } else {
        for (GeneralTreeNode child : this.children) {
            return child.findNode(targetName);
        }
    }
    // no node containing the string could be found
    return null;  
  }

唯一的问题是,这似乎常常错误地 return null,而实际上确实存在一个节点。好像最后一行return null太贪心了

在此设置几个断点并观察它表明它似乎只下降到最低深度,直到一个节点没有子节点,在这种情况下它只是 return 为空。

任何人都可以提供有关如何改进的建议吗?

将您的代码更改为:

public GeneralTreeNode findNode(String targetName) {          
    if (this.name.equals(targetName)) {
        return this;
    } else {
        for (GeneralTreeNode child : this.children) {
            GeneralTreeNode childResult = child.findNode(targetName);

            if (childResult != null) {
                return childResult;       // only return if you really found something
            }
        }
    }

    // no node containing the string could be found
    return null;  
}

您只想 return 子搜索的结果,如果它真的找到了东西。

这样实现的话,代码的可读性就没有了。在助手 class 中可以更好地实现树遍历,并且将 ROOT 元素与 target_name 一起传递。

如果您以这种方式 return null,则类似于 node is null 实际上它不是。另一方面,当你使用"doer"或"processor"method/function时,它可以return真言"I cannot find anything"。

不过,您的代码似乎没问题。我只是重写它。

static Node search(Node node, String nodeName) {
   if (node.getName().equals(nodeName)) return node;

   List<Node> children = node.getChildren();
   foreach(Node child : children) { 
      Node resultChild = search(child, nodeName);
      if (resutlChild != null) return resultChild;

   }

   return null;

}