Java:我的一般树遍历实现有什么问题?

标签 java tree

我的任务是从字符串 targetName 给出的通用树中查找并返回特定节点。看看下面我的实现:

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

唯一的问题是,当事实上节点确实存在时,这似乎经常错误地返回 null。就好像最后一行 return null 太贪婪了。

在这个节点上设置几个断点并观察它,它似乎只会下降到最低深度,直到节点没有子节点,在这种情况下它只是返回 null。

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

最佳答案

将代码更改为:

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

您只想在子搜索确实找到某些内容时返回结果。

关于Java:我的一般树遍历实现有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32878568/

相关文章:

java - 测试方法接受其他子类作为参数

java - 以编程方式获取 JVM 的 -Xss 最大堆栈大小分配值?

ruby-on-rails - 工厂女孩和血统

sql - Postgresql 复制树表内的数据

Python 元素树写入新文件

java - 提取大量 zipper

java - 可以使用正则表达式来获取子字符串吗?

java - Mockito 的when() 没有 stub 父类(super class)的方法

c++ - 路径树到树结构

javascript - CSS/Javascript 中的树形图像布局