Linked Questions

Popular Questions

Need help understanding these method parameters used in the constructor

Asked by At

Working on an assignment. Taking classes online and I've emailed my prof with the same question but I'm hoping to get a quicker response from you wonderful people here (as I only have 2 hours per day that I can work on school and Ive hit a roadblock).

Assignment is to finish the code for a binary search tree and blah blah implement some stuff.

I'm hung up on one chunk of code that I just cant understand.

This is a code snippet from the LinkedBinaryTree class that was provided. LinkedBinaryTree relies on a BinaryTreeNode class for the nodes.

public class LinkedBinaryTree<T> implements BinaryTreeADT<T>, Iterable<T>
{
   protected BinaryTreeNode<T> root; 
   protected int modCount;
}

//Constructors

public LinkedBinaryTree() 
{
    root = null;
}  

public LinkedBinaryTree(T element) 
{
    root = new BinaryTreeNode<T>(element);
}

public LinkedBinaryTree(T element, LinkedBinaryTree<T> left, 
        LinkedBinaryTree<T> right) 
{
    root = new BinaryTreeNode<T>(element);
    root.setLeft(left.root);
    root.setRight(right.root);
}

This is primarily what I fail to grasp.

root.setLeft(left.root);

root.setRight(right.root);

What is .root and how does that work.

The variable is being used in two places? is this some kind of recursion/magic that I just haven't encountered yet? (And currently fail to understand) If so, I will get reading let me know and point me in the right direction.

I will post the code for the BinaryTreeNode methods below. I don't understand these parameters that are being passed.

root is a variable of the type BinaryTreeNode but in its use it is passing a LinkedBinaryTree either left or right as the parameters for a method that requires a variable of type BinaryTreeNode

public class BinaryTreeNode<T>{

    protected T element;
    protected BinaryTreeNode<T> left, right;

//Constructors

public BinaryTreeNode(T obj) 
{
    element = obj;
    left = null;
    right = null;
}

public BinaryTreeNode(T obj, LinkedBinaryTree<T> left, LinkedBinaryTree<T> right) 
{
    element = obj;
    if (left == null)
        this.left = null;
    else
        this.left = left.getRootNode();

    if (right == null)
        this.right = null;
    else
        this.right = right.getRootNode();
}

And the methods in question

public void setLeft(BinaryTreeNode<T> node)
{
    left = node;
}

public void setRight(BinaryTreeNode<T> node) 
{
    right = node;
}

Related Questions