Sum of prefix trees

Posted by Bomas on Thu, 12 Dec 2019 15:51:27 +0100

New prefix tree*/
1. Define data structure: 26 child nodes of the root node, optional, which word letter is indicated by index
2. Create a new insert. If the root node is empty, return it directly. If the string to be inserted is empty, set the value of the current tree node to the given value (there are two situations when the current string is empty: 1. Given string key=null;value=v;2.key="String",Value=num. after the tree is built, the value of the current node is equal to the given value)

3. Sum of prefix accumulation

When the current patch search is completed, record the value of the current node, and then accumulate the values of each child node of the current node.

class MapSum {

    private class Node{
        //1. Represents the optional 26 child nodes
        Node[] child=new Node[26];
        //2, the value value of the setting to be inserted
        int value;
    }
    //Create a new node root node object
    private Node root=new Node();
    
    
    /** Initialize your data structure here. */
    public MapSum() {
        
    }
    //Start building prefix tree
    public void insert(String key, int val) {
       insert(key,root,val); 
    }
    private void insert(String key,Node node,int val){
        if(node==null) return;
        if(key.length()==0){
            node.value=val;
            return;
        }  
        int index=indexOfChar(key.charAt(0));
        if(node.child[index]==null){
            node.child[index]=new Node();
        }
        insert (key.substring(1),node.child[index],val);
    }
    //Start to sum. If there is a string with a given prefix in the tree, add the value of the leaf node corresponding to their string
    public int sum(String prefix) {
        return sum(prefix,root);
    }
    private int sum(String prefix,Node node){
        if(node==null) return 0;
        if(prefix.length()!=0){
            int index=indexOfChar(prefix.charAt(0));
            return sum(prefix.substring(1),node.child[index]);
        }
        //Prefix string lookup complete
        int sum=node.value;
        for(Node child: node.child){
            sum+=sum(prefix,child);
        }
        return sum;
    }
    
    private int indexOfChar(char c){
        return c-'a';
    }
}

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum obj = new MapSum();
 * obj.insert(key,val);
 * int param_2 = obj.sum(prefix);
 */

 

Topics: Big Data