gpt4 book ai didi

java - 图论,尝试计算树中节点时的空指针

转载 作者:行者123 更新时间:2023-11-30 03:22:06 26 4
gpt4 key购买 nike

public class BuildTree {

private HashMap<Integer, LinkedList<Integer>> tree;
private int edges;

public static void main(String[] args) {
BuildTree bt = new BuildTree();
bt.run();
}

private void run() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int treeRoot = 0;
tree = new HashMap<>();
edges = 0;
for (int i = 0; i < m; i++) {
int adjacent = in.nextInt();
int root = in.nextInt();
if (i == 0) {
treeRoot = root;
}
if (!tree.containsKey(root)) {
tree.put(root, new LinkedList<>());
tree.get(root).add(adjacent);
} else {
tree.get(root).add(adjacent);
}
}

// tree is built correctly
// tree.get(1).forEach(System.out::print);
// System.out.println();
// tree.get(2).forEach(System.out::print);
// System.out.println();
// tree.get(3).forEach(System.out::print);
// System.out.println();
// tree.get(6).forEach(System.out::print);
// System.out.println();
// tree.get(8).forEach(System.out::print);

System.out.println(treeSize(2)); //expecting 3
}

private int treeSize(Integer i) {
int size = 1;
if (tree.get(i).isEmpty() || tree.get(i) == null) { //throws null pointer exception
return size;
} else {
Iterator<Integer> it = tree.get(i).iterator();
while (it.hasNext()) {
Integer subRoot = it.next();
size += treeSize(subRoot); //issue flagged here by console, directs to problematic if statement above
}
}
return size;
}
}

控制台输入如下:
10 9
2 1
3 1
4 3
5 2
6 1
7 2
8 6
9 8
10 8

我已经通过打印每个节点的相邻整数的 LinkedList 来检查树是否正确构建。我引用某个根节点计算树大小的方法不断抛出空指针异常。我是图论方面的新手,我不知道如何继续。

最佳答案

你的答案是正确的,但问题还有另一种解决方案

if (tree.get(i).isEmpty() || tree.get(i) == null)

抛出NullPointerException,但条件顺序错误,如果这样做:

if (tree.get(i) == null || tree.get(i).isEmpty())

不会出现NullPointerException
为什么:因为条件是从左到右检查的,当tree.get(1) == null时,则为true,所以它将是:

if (true || tree.get(i).isEmpty())

编译器无法解决第二部分的问题,因为它必须为真:

true || something || something_else = true

关于java - 图论,尝试计算树中节点时的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31104074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com