Nice and clean recursion java code


  • 2
    A
    enter code here 
    class TrieNode {
          TrieNode[] children;
          boolean flag;
          public TrieNode() {
          children=new TrieNode[26];
          flag=false;
               }
    }
     public class Trie {
    private TrieNode root;
    public Trie() {
        root = new TrieNode();
    }
    public void insert(String word) {
        insert(root,word);
    }
    private void insert(TrieNode p, String word){
        if(word.length()==0){
            p.flag=true;
            return;
        }  
        char c=word.charAt(0);
        if(p.children[c-97]==null){
            TrieNode toInsert=new TrieNode();
            p.children[c-97]=toInsert;
        }
        insert(p.children[c-97],word.substring(1));
    }
    public boolean search(String word) {
        if(word==null)  return false;
        return search(root,word);
    }
    private boolean search(TrieNode p,String word){
        if(word.length()==0){
            if(p.flag)
                return true;
            else
                return false;
        }
        char c=word.charAt(0);
        if(p.children[c-97]==null)
            return false;
        else
            return search(p.children[c-97],word.substring(1));
    }
    public boolean startsWith(String prefix) {
        if(prefix==null)    return false;
        return startsWith(root,prefix);
    }
    private boolean startsWith(TrieNode p, String prefix){
        if(prefix.length()==0)    return true;
        char c=prefix.charAt(0);
        if(p.children[c-97]==null)
            return false;
        else
            return startsWith(p.children[c-97],prefix.substring(1));
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.