我在节点类中为树数据结构收到Stackoverflow错误。我知道原因,但我似乎无法解决它。
public class Node {
Node right;
Node left;
String element;
Node parent;
public Node(){
right = new Node();
left = new Node();
}
}
因为我在构造函数中构造新的节点,我得到了堆栈溢出。如何构造我的构造函数并避免此错误?
答案 0 :(得分:3)
您可以在实际存在的情况下按需创建节点。
public class Node {
Node left, right; // created as required
String element;
Node parent;
public Node(Node parent, String element) {
this.parent = parent;
this.element = element; // if you don't have an element you don't need a Node.
}
}
注意:您很可能不需要parent
字段,大多数实现都不使用它。
public class Node {
Node left, right; // created as required
String element;
public Node(String element) {
this.element = element; // if you don't have an element you don't need a Node.
}
public void setLeft(Node left) { this.left = left; }
public void setRight(Node right) { this.right = right; }
}
e.g。
Node d = new Node("d");
d.setLeft(new Node("a"));
d.setRight(new Node("z"));
答案 1 :(得分:1)
您应该删除递归构造函数调用,如下所示。
public Node(){
right = null;
left = null;
}
特定树的装配应该通过从类外部或通过getter和setter函数分配子项来完成。
答案 2 :(得分:1)
不要new Node
在构造函数中,它永远不会结束直到stackoverflow或堆内存不足,你可以这样做:
left
,right
传递给构造函数:代码:
public class Node {
Node right;
Node left;
String element;
Node parent;
public Node(Node left, Node right){
this.left = left;
this.right = right;
}
}
setter
:代码:
public class Node {
Node right;
Node left;
String element;
Node parent;
public Node(){
}
public void setLeft(Node left) {
this.left = left;
}
public void setRight(Node right) {
this.right = right;
}
}