Reputation: 2619
In the following program,
what does this mean left.parent = this;
I know it says make parent of left child to be 'this
' but what exactly is this
. this refers to current instance method right? but can anyone explain a bit better.
public class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode root;
private int size = 0;
public TreeNode(int d) {
data = d;
size = 1;
}
public void setLeftChild(TreeNode left) {
this.left = left;
if (left != null) {
left.root= this;
}
}
Would the same function setLeftChild
above be represented like the function below:
void setLeftChild(TreeNode node)
{
if(root == null)
{
this.root = node;
}
else
{
this.left = node;
}
}
Upvotes: 1
Views: 984
Reputation: 44814
Assuming you did
TreeNode a = new TreeNode (1);
At this time a's left
, right
and root
are null
if you did
TreeNode b = new TreeNode (b);
a.setLeftChild (b);
then now a's right
and root
are still null but left
is b
and b's root
is now a
Upvotes: 1
Reputation:
No the bottom code is not correct. In the bottom implementation what you do is you make the left child node actually the parent node of your class. If the node you are in already is not the root node then the left child is set correctly, but the left child does not get its parent set correctly.
The image below is the result of executing the code on the bottom
The image below is the result of executing the top block (which is correct)
Upvotes: 3
Reputation: 325
this is a reference to current object http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Upvotes: -2