Binary Search Tree Insert cannot find symbol Error

Viewed 82

I am making a program that inserts characters to a binary tree. I used other source codes as reference but I keep encountering the error that it cannot find symbol 'key' even if it exists. I am also not quite sure with the algorithm of my program so if you have any suggestions it would be greatly appreciated.

Error:

.\BST.java:28: error: cannot find symbol
            if (key < n.key) //** error
                       ^
  symbol:   variable key
  location: variable n of type BTNode<T>
  where T is a type-variable:
    T extends Object declared in class BST
.\BST.java:40: error: cannot find symbol
        if (key < p.key) //** error
                   ^
  symbol:   variable key
  location: variable p of type BTNode<T>
  where T is a type-variable:
    T extends Object declared in class BST

Here is my Main Class

public class Test 
{
    public static void main(String args[]) 
    {
        BST<Character> bst = new BST<>(); // instantiate BST object
        
        // insert values to bst
        bst.insert('A');
        bst.insert('B');
        bst.insert('C');
        bst.insert('D');
        bst.insert('E');
        bst.insert('F');
        
        // print bst
        bst.toString();
    }
}

and my BST class

public class BST<T> extends BT<T>
{
    public void insert(char key) 
    {
        int level = 0;
        
        if (root == null)
        {
            root = new BTNode(key);
            return;
        }
        
        BTNode<T> n = root;
        BTNode<T> p = null;
        
        while (n != null) 
        {
            p = n;
            
            if (key < n.key) //** error
            {
                n = n.left;
            }
            else
            {
                n = n.right;
            }
            
            level++;
        }
        
        if (key < p.key) //** error
        {
            p.left = new BTNode(key);
            height = level + 1;
        }
        else
        {
            p.right = new BTNode(key);
            height = level + 1;
        }
    }
}

Hope you can help me out with this. Thanks!

1 Answers

Looking at the code you post and the error, as n and p are instances of BTNode, it seems that the class BTNode has no attribute named key, or that attribute is not visible/accessible from class BST.

Can you review that or provide also the source code of BTNode?

Related