正在查看一个 SO 问题,我建议递归地填充节点网格,我想我应该自己尝试代码,以下内容不断溢出
public class Node {
private Node left;
private Node right;
private Node up;
private Node down;
private int x;
private int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
public static void buildGrid(Node node) {
fill(node);
}
private static void fill(Node node) {
fillLeft(node);
fillRight(node);
}
private static void fillRight(Node node) {
if (node.right != null || node.x > 10)
return;
node.right = new Node(node.x + 1, node.y);
fill(node.right);
}
private static void fillLeft(Node node) {
if (node.left != null || node.x <= 0)
return;
node.left = new Node(node.x - 1, node.y);
fill(node.left);
}
public static void main(String[] args) {
Node node = new Node(5, 5);
buildGrid(node);
}
太晚了,我可能错过了非常明显的,但为什么会溢出?第一次fillLeft
返回,fill(node.left)
第二次调用fillLeft(node.left)
should 立即返回 since node.left.right != null
。相同fillRight
,无法弄清楚这里有什么问题。
堆栈跟踪
Exception in thread "main" java.lang.StackOverflowError
at Node.<init>(Node.java:16)
at Node.fillLeft(Node.java:42)
at Node.fill(Node.java:26)
at Node.fillRight(Node.java:35)
at Node.fill(Node.java:27)
at Node.fillLeft(Node.java:43)
at Node.fill(Node.java:26)
at Node.fillRight(Node.java:35)
at Node.fill(Node.java:27)
at Node.fillLeft(Node.java:43)
at Node.fill(Node.java:26)
at Node.fillRight(Node.java:35)
at Node.fill(Node.java:27)
at Node.fillLeft(Node.java:43)
at Node.fill(Node.java:26)
at Node.fillRight(Node.java:35)
at Node.fill(Node.java:27)
at Node.fillLeft(Node.java:43)
at Node.fill(Node.java:26)
at Node.fillRight(Node.java:35)
at Node.fill(Node.java:27)
at Node.fillLeft(Node.java:43)
at Node.fill(Node.java:26)
at Node.fillRight(Node.java:35)
at Node.fill(Node.java:27)
at Node.fillLeft(Node.java:43)