1

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;
        }
    }
  • Is the implementation correct? first and 2nd?
    • If not then what is wrong with the 2nd implementation? and vice versa
  • What is the difference between first and 2nd implementation?
1
  • no, node is not necessarily the same as this and it is the left's root that is being set. Commented Apr 30, 2014 at 2:34

3 Answers 3

3

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

enter image description here

The image below is the result of executing the top block (which is correct)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

so which implementation is correct? And can you tell me working of my first and 2nd method? what happens? and how I am wrong in 1 of them
as to which implementation is correct depends upon your business logic. What are you wanting to achieve? I would say that if you are setting the left of A to be B, then the right of B should be A - eh?
-2

this is a reference to current object http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

1 Comment

@sps It doesnt satisfy my question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.