In a binary search tree that takes a simple object…..when creating the getter and setter methods for the left, right, and parent. There are concerns about what is happening when a parent node is set. Code bellow…
The code:
public void setParent(Person parent) {
parent = new Person( parent.getName(), parent.getWeight());
The example code that inspired the code:
public void setParent(Node parent) {
this.parent = parent;
}
You’re creating what is essentially a clone of the parent object. This is different from just saving the pointer to the parent object.
Obviously, you’ll be taking more memory space by duplicating the parent object. More importantly, you’re not duplicating the parent’s references. So if you try to traverse the tree, go to a node’s parent, then try to visit its other children, you draw a bunch of null pointers.
The
this.parentis a reference to the current object’sparentpointer.It doesn’t actually mean that
thisis a parent. In fact,this.parentis used to distinguish the localparentpointer from the incoming parameterparent.