mission-peace / interview

Interview questions
Apache License 2.0
11.08k stars 5.17k forks source link

New implementation for trie delete using recursion #220

Open mukeshsingal opened 5 years ago

mukeshsingal commented 5 years ago

https://github.com/mission-peace/interview/blob/94be5deb0c0df30ade2a569cf3056b7cc1e012f4/src/com/interview/suffixprefix/Trie.java#L122

public void remove(String word) {
        if (word == null || word.length() == 0) {
            return;
        }
        removeUtil(word, root);
    }

    public boolean removeUtil(String word, TrieNode current) {
        if (word.length() == 0) {
            current.endOfWord = current.children.size() == 0;
            return current.endOfWord;
        }

        char c = word.charAt(0);
        if (current.children.get(c) != null && removeUtil(word.substring(1), current.children.get(c))) {
            current.children.remove(current.children.get(c).key);
            return current.children.size() == 0 && !current.endOfWord;
        }

        return false;
    }
Chiranjivee commented 5 years ago

Looks good

dgr8akki commented 5 years ago

Please pay kind attention towards indentation even while copying and pasting.