【问题标题】:How to find a specific node in a non binary Tree?如何在非二叉树中找到特定节点?
【发布时间】:2023-03-13 03:14:02
【问题描述】:

我有一棵包含多个节点的树。每个节点都有一个父节点(或在根的情况下为 null)、一个名称(名称)和一个将子节点的名称映射到子节点对象的 HashTable(子节点)。

给定节点的字符串名称,我想创建一个方法来遍历树以查找特定节点并返回它。如果节点不存在则返回null。

我认为递归方法是最好的。到目前为止,我有这个:

public Node findNode(Node n, String s) {
   if (n.name == s) {
       return n;
   } else {
       for (Node child: n.children.values()) {
            findNode(child, s);
       }
     }
}

我不确定在哪里放置 null 语句。

【问题讨论】:

    标签: java tree


    【解决方案1】:

    如果孩子有,则归还。如果没有,则返回null。

    public Node findNode(Node n, String s) {
        if (n.name == s) {
            return n;
        } else {
            for (Node child: n.children.values()) {
                Node result = findNode(child, s);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }
    

    【讨论】:

    • 一个很好的答案,我想指出,“ if (result != null){... ”里面的 for 对于避免返回空值而不是搜索的非空值很重要。谢谢!
    【解决方案2】:

    这里是使用Optional 搜索节点的Java 11+ 版本。

    public Optional<Node> search (Node node, String needle) {
        if (node.getValue().equals(needle)) {
            return Optional.of(node);
        } else {
            for (var child : node.getChildren()) {
                var result = search(child, needle);
                if (result.isPresent()) {
                    return result;
                }
            }
        }
    
        return Optional.empty();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-08
      • 2019-05-16
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多