0

I'm having trouble with some binary tree stuff, specifically, I can't get a method defined in the original class to work in another.

public class BTNode<E>
{// Invariant of the BTNode<E> class:
   //   1. Each node has one reference to an E Object, stored in the instance
   //      variable data.
   //   2. The instance variables left and right are references to the node's
   //      left and right children.
   private E data;
   private BTNode<E> left, right;   

   public BTNode(E initialData, BTNode<E> initialLeft, BTNode<E> initialRight)
   {
      data = initialData;
      left = initialLeft;
      right = initialRight;
   }       


   public E getData( )   
   {
      return data;
   }

Why am I unable to use the getData(),getLeft(), getRight() methods in another class? for example:


import java.util.*;
public class BinSearchTree {

  private BTNode<Pair<Integer,String>> root;

  public BinSearchTree() { 
    root = null;
  }

  public BinSearchTree(BTNode<Pair<Integer,String>> aNode){
     this.root = aNode; 
  }

  public BinSearchTree(Pair<Integer,String> aPair) { 
    this.root = new BTNode<Pair<Integer,String>>(aPair,null, null);
  }

  public boolean insert(Pair<Integer,String> aPair){  
    Integer key = aPair.getX();
    if (this.getData( ).getX() == key){return false;}
    if (this.getData().getX()<key){
      if (this.getLeft()== null){this.setLeft(BTNode(aPair, null, null));}
      else{this.getLeft().insert(aPair);}}
    else{
      if (this.getRight()== null){this.setRight(BTNode(aPair, null, null));}
      else{this.getRight().insert(aPair);}}

    return true; 
  }

The use of getData in the insert function is causing a "cannot find symbol" error. Any advice would be greatly appreciated

new2java
  • 39
  • 5

2 Answers2

2

The keyword this refers to the current class you are in. You are using this inside BinSearchTree where there is no function defined called getData()

You should use root.getData() instead since root is an instance of the class BTNode therefore it has the function getData()

kecoliva
  • 80
  • 1
  • 11
1

Instead of this.getData() you need root.getData(), same with this.getLeft() (root.getLeft()) and this.getRight() (root.getRight()).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249