二叉查找树
定义;一棵二叉查找树(BST)是一棵二叉树,每个节点的键都大于其左子树中的任意节点的键而小于右子树的任意节点的键
public class BST {
private Node root; //二叉树的根节点
static class Node{
private String key; //键
private String val; //值
private Node left,right; //指向子树的链接
private int N; //以该节点为根的子树中的节点总数
public Node(String key,String val,int N) {
this.key=key;
this.val=val;
this.N=N;
left=right=null;
}
}
//查找
public String get(String key) {
return get(root,key);
}
private String get(Node x,String key) {
if(x==null) {
return null;
}
int cmp=key.compareTo(x.key);
if(cmp<0) return get(x.left,key);
else if(cmp>0) return get(x.right,key);
else return x.val;
}
//插入
public void put(String key,String val) {
root =put(root,key,val);
}
private Node put(Node x,String key,String val) {
//如果key存在于以x为根节点的子树中则更新它的值
//否则将以key和val为键值对的新节点插入到该子树中
if(x==null) return new Node(key,val,1);
int cmp=key.compareTo(x.key);
if(cmp<0) x.left=put(x.left,key,val);
else if(cmp>0) x.right=put(x.right,key,val);
else x.val=val;
return x;
}
public static void main(String[] args) {
BST bst=new BST();
String[] s= {"G","F","I","D","P","W","N","M"};
for(int i=0;i<s.length;i++) {
bst.put(s[i], null);
}
pre(bst.root);
}
//前序遍历
public static void pre(Node node) {
if(node.left!=null) {
pre(node.left);
}
System.out.print(node.key+" ");
if(node.right!=null) {
pre(node.right);
}
}
}