【发布时间】:2016-02-24 08:08:21
【问题描述】:
我有 TreeNode 类——实现非二叉树的节点(List<TreeNode> children)。
我需要在它的子节点中找到具有给定数据的第一个节点。我写了一些方法,但显然有一些问题(java.lang.AssertionError: Failed to find a child with not-null data: expected:<2> but was:<null>)。 (如果数据为空,我需要用空数据返回第一个孩子)。
public TreeNode findChild(Object data) {
if (data == null) {
Iterator<TreeNode> a = getChildrenIterator();
TreeNode tmp;
while (a.hasNext()) {
tmp = a.next();
if (tmp.getData()==null) return tmp;
tmp.findChild(data);
}
}else
{
Iterator<TreeNode> a = getChildrenIterator();
TreeNode tmp;
while (a.hasNext()) {
tmp = a.next();
if (data.equals(tmp.getData())) return tmp;
tmp.findChild(data);
}
}
return null;
}
【问题讨论】:
-
可能是你的树太大了,因为你(可能)每个节点都有很多递归调用。
-
@dbrown93 抱歉,现在还有一个错误
-
如果
tmp.getData()不匹配,则重复出现。递归是死代码,因为你不对结果做任何事情,while 循环继续。 -
@Sylwester 请告诉我我需要在这里修复什么
标签: java algorithm recursion tree