# leetcode: 鍵值映射

### 題目描述:

=================================================

==================================================

### java算法:

``````
//實現三向查找樹

class MapSum {

class Node{
char c;
Node left;
Node right;
Node mid;
Integer val;
Node(char c, Integer val){
this.c = c;
this.val = val;
}
}

private Node root;

/** Initialize your data structure here. */
public MapSum() {
}

private Node insert(Node x, String key, int val, int d){
if(x == null){
x = new Node(key.charAt(d), null);
}
if(x.c > key.charAt(d)){
x.left = insert(x.left, key, val, d);
}
else if(x.c < key.charAt(d)){
x.right = insert(x.right, key, val, d);
}
else if(d < key.length() - 1)
x.mid = insert(x.mid, key, val, d+1);
else
x.val = val;
return x;
}

public void insert(String key, int val) {
root = insert(root, key, val, 0);
}

// 搜索prefix對應的終止節點
private Node searchNode(Node x, String prefix, int d){
if(x == null)
return null;
if(x.c > prefix.charAt(d))
return searchNode(x.left, prefix, d);
else if(x.c < prefix.charAt(d))
return searchNode(x.right, prefix, d);
else if(d < prefix.length()-1)
return searchNode(x.mid, prefix, d+1);
else
return x;
}

private int sum(Node x){
if(x == null)
return 0;
int sumVal = 0;
if(x.val != null)
sumVal += x.val;
return sumVal + sum(x.left) + sum(x.mid) + sum(x.right);
}

//以prefix起始的字符串包括prefix(如果prefix存在與前綴樹中)以及mid節點之後的所有節點
public int sum(String prefix) {
Node start = searchNode(root, prefix, 0);
if(start == null)
return 0;
int sumVal = 0;
if(start.val != null)
sumVal += start.val;
return sumVal + sum(start.mid);
}
}

``````