Search code examples
javaoopdata-structuresbinary-search-tree

Implementing an insert into a Binary Search Tree with a String Object JAVA


Im trying to implement a program that adds Word Objects(string word, string meaning) into a Binary Search Tree Alphabetically. I know how to implement a Binary Search Tree with an integer attribute but I'm having difficulties doing it with strings.

public class WordInfo {
    public String word;
    public String meaning;
    public WordInfo left;
    public WordInfo right;
    public WordInfo(String word, String meaning){
        this.word = word;
        this.meaning = meaning;
        left=right = null;
    }
    
}
public class Dictionary {

     WordInfo root;
     int count;
    
    public Dictionary() {
        root = null;
    }
    
    public void add(String word, String meaning) {
        WordInfo w = new WordInfo(word, meaning);
        if (root == null) {
            root = w;
        }
        WordInfo curr, parent;
        parent = curr = root;
        while (curr != null) {
            parent = curr;
            if (word.compareToIgnoreCase(curr.word) < 0) {
                curr = curr.left;
            } else {
                curr = curr.right;
            }
        }
        if (word.compareToIgnoreCase(parent.word) < 0) {
            parent.left = w;
        } else {
            parent.right = w;
        }
        
    
    } }

When I try to add these WordInfo objects into my main program nothing is being added.


Solution

  • In your code snippet, you haven't returned if empty dictionary.

    if (root == null) {
            root = w;
    }
    

    have to be replaced with

    if (root == null) {
            root = w;
            return;
        }
    

    So if the root is null, you add an element and return it, of course you can increment the count when new element added.