Question

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?
Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top