2015-10-01 27 views
1

我的任务是查找并返回由字符串targetName给出的一般树中的特定节点。快来看看下面我的实现:Java:我的一般树遍历实现有什么不正确?

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太贪婪了。

在这个问题上找到几个断点并观察它,结果表明它似乎只能下到最低深度,直到一个节点没有子节点,在这种情况下它只是返回null。

任何人都可以提供有关如何改善此问题的建议吗?

+1

您需要检查findNode的返回值,并且只有在* not * null时才返回。 –

回答

2

你的代码改成这样:

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; 
} 

你只想从子搜索返回的结果,如果真的发现了什么。

+0

消除'return null'语句会导致编译错误,不是吗?这开启了没有价值被返回的可能性。 – ReactingToAngularVues

+0

@EchoLogic我对“改变这一部分”非常具体。没有必要复制没有改变的代码,我想。但它也没有伤害。谢谢蒂姆。 –

+0

这很好,谢谢你的帮助。它看起来不错。显然,我在处理递归方法时低估了空检查的重要性。干杯。 – ReactingToAngularVues

0

如果以这种方式实现,代码的可读性将消失。树遍历最好在助手类中实现,并将ROOT元素与target_name一起传递。

如果你以这种方式返回null,它就像node是null实际上它不是。另一方面,当你使用“doer”或“processor”方法/函数时,它可以返回真实的“我找不到任何东西”。

尽管如此,你的代码似乎没问题。我只是重写它。

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; 

} 
+0

'foreach'这不是一个java语法。 – YoungHobbit

+0

这只是编写在纸上,为或foreach试图告诉它正在循环:) –

+0

你应该这样写:'for(Node child:children){'。 – YoungHobbit