Reputation: 631
Im getting a Stackoverflow error in my node class for a tree data structure. I am aware of the cause, however I cannot seem to fix it.
public class Node {
Node right;
Node left;
String element;
Node parent;
public Node(){
right = new Node();
left = new Node();
}
}
because Im constructing new Nodes within the constructor, I get a stack overflow. How can I structure my constructor and avoid this error?
Upvotes: 0
Views: 612
Reputation: 12521
Don't new Node
itself in its constructor, it'll never end till stackoverflow or heap out of memory, you could do it:
left
, right
to constructor:Code:
public class Node {
Node right;
Node left;
String element;
Node parent;
public Node(Node left, Node right){
this.left = left;
this.right = right;
}
}
setter
:Code:
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;
}
}
Upvotes: 1
Reputation: 17605
You should delete the recursive constructor calls as follows.
public Node(){
right = null;
left = null;
}
The assembly of a specific tree should be done by assigning the children from perhaps outside the class or via getter and setter functions.
Upvotes: 1
Reputation: 533660
You can create the Nodes on demand when they actually exist.
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.
}
}
Note: most likely you don't need the parent
field, most implementations don't use it.
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"));
Upvotes: 3