Search code examples
javabinary-search-treetostringhashcode

Binary Tree toString prints hashcode even after override


I made a program that inserts characters (letters) into a binary search tree. I am not encountering any errors but when I call the toString method, it only prints a part of the output with the hashcode of ht=10 [K=G R=BTNode@5b6f7412]. I might have overlooked something so it would be greatly appreciated if you could help me out. Thanks!

Expected Output (not the exact output but in this format) ht=2 [K=A L=[K=B R=[K=C]] R=[K=D L=[K=E]]]

toString method

public String toString()
    {
        String s = "";
        BTNode<T> n = root;
        
        if (n == null)
        {
            return "";
        }
        
        if (n != null) 
        {
            s = "ht=" + height + " [K=" + n.info;
            
            if (n.left != null)
            {
                s = s + " L=" + n.left.toString() + "]"; 
            }
            if (n.right != null)
            {
                s = s + " R=" + n.right.toString() + "]";
            }
        }
        return s;
    }

Main Class

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 bst1
        System.out.println(bst.toString());
    }


Solution

  • You have to write a method with the exact signature public String toString() in BTNode.

    Writing public String toString(BTNode<N>) accomplishes nothing.