踏踏实实积累,不要浮躁!!!
思想:利用二叉树来存储散列表中的值,提供高效的put get 操作
说明:下面的代码只是帮助理解散列表的工作原理,工程上一般都是用红黑树来实现平衡的二叉排序树
put 操作内部利用的是get 操作,如果能查找到则更新该节点的value值,如果没有找到根据大小关系在下面插入该节点
package search;
import edu.princeton.cs.algs4.StdOut;
/**
* 基于BST 二叉查找数来构造的散列表
* @param <Key> 用于比较的键
* @param <Value> 用于比较的存储值
*/
public class BST<Key extends Comparable<Key>,Value> {
private Node root;
/**
* N 以该节点为根的子树中节点的总数
*/
private class Node{
private Key key;
private Value value;
private Node left,right;
private int N;
public Node(Key key,Value val,int N){
this.key = key;
this.value = val;
this.N = N;
}
}
public int size(){
return size(root);
}
public int size(Node root){
if(root == null){
return 0;
}else {
return root.N;
}
}
private void print(Node x) {
if (x == null){
return;
}
print(x.left);
StdOut.println(x.key);
print(x.right);
}
public Value get(Key key){
return get(root,key);
}
public Value get(Node x,Key key){
if(x == null){
return null;
}
int cmp = x.key.compareTo(key);
if(cmp < 0){
return get(x.right,key);
}else if(cmp > 0){
return get(x.left,key);
}else {
return x.value;
}
}
public void put(Key key,Value val){
root = put(root,key,val);
}
private Node put(Node x,Key key,Value value){
if(x == null){
return new Node(key,value,1); // 如果二叉树是空的则构造一个新的返回
}
int cmp = key.compareTo(root.key);
if(cmp < 0){
x.left = put(x.left,key,value);
}else if(cmp > 0){
x.right = put(x.right,key,value);
}else {
x.value = value;
}
x.N = size(x.left) + size(x.right) + 1;
return x;
}
public static void main(String[] args) {
BST bs = new BST();
bs.put("a",1);
bs.put("b",2);
bs.put("c",3);
bs.put("d",4);
bs.put("e",5);
bs.put("f",6);
// bs.print(bs.root);
int val = (Integer) bs.get("f");
System.out.println(val);
}
}
下一篇文章会介绍平衡的二叉查找数 红黑树