本文我们继续搭建二叉树剩下一部分方法
API:
要实现这些方法,我们首先需要对各节点进行一个计数,找出各节点的子节点数目(包括其本身)。
我们在Node构造方法里加入count作为计数器,并在put方法里更新各节点计数
private class Node {
private Key key;
private Value value;
private Node left;
private Node right;
private int count;
private Node(Key key, Value value, int count) {
this.key = key;
this.value = value;
this.count = count;
}
}
// put a key-value pair into the tree
public void put (Key key, Value value) {
root = insert(key, value, root);
}
private Node insert(Key key, Value value, Node x) {
if (x == null) {
return new Node(key, value, 1);
}
if (x.key.compareTo(key) > 0) { // smaller, move to the left
x.left = insert(key, value, x.left);
} else if (x.key.compareTo(key) < 0) { // larger, move to the right
x.right = insert(key, value, x.right);
} else {
x.value = value; // key existed, replace it
}
x.count = size(x.left) + size(x.right) + 1;
return x;
}
put里面使用的size方法见下文
1 size
用户调用的size:count存储该节点所有子节点个数,因此总节点树即为根节点count值,注意如果根节点为null需要额外判断
public int size() {
return size(root);
}
private int size(Node x) {
if (x == null) {
return 0;
} else {
return x.count;
}
}
私有的size方法应用在put里用于更新各节点计数。左子树节点数+右子树节点数+1(自己)即为该节点为根的子树的总节点数
2 select
// return the kth smallest key
public Key select(int k) {
Node x = select(k, root);
if (x == null) {
return null;
}
return x.key;
}
private Node select(int k, Node x) {
if (x == null) {
return null;
}
int rank = size(x.left);
if (rank == k) { // find the correct index
return x;
} else if (rank > k) { // move to the left
return select(k, x.left);
} else { // move to the right
return select(k - rank - 1, x.right);
}
}
在这里我们要注意每个节点的count代表的是其所有子节点个数,包括左节点和右节点。要找到该节点在树中排名,应查看其左子节点的排名。(最左端节点,即最小值,排名为0)
基线条件:1 如果达到树底(x为null),说明整个二叉树键的数量小于k,查找越界
2 如果对应索引等于k,说明找到键
状态转移方程:rank为左子节点排名,如果rank大于目标值左移,继续查找。如果rank小于目标值,向右递归查找时要(-rank-1),代表减去小于右节点的根节点左节点,和根节点自身。
3 rank
// find the rank of a given key
public int rank(Key key) {
return rank(key, root);
}
private int rank(Key key, Node x) {
if (x == null) {
return 0;
}
int cmp = key.compareTo(x.key);
if (cmp == 0) { // find the key
return size(x.left);
} else if (cmp > 0) { // smaller, move to the right
return size(x.left) + 1 + rank(key, x.right);
} else { // larger, move to the left
return rank(key, x.left);
}
}
基线条件:
如果x为null,即查到树底还没有找到对应键,返回0
如找到对应键,返回其左子节点数
状态转移方程:
如果当前节点键大于目标键,查找左子树
如果当前节点键小于目标键,查找右子树,同时要加上size(x.left) + 1,代表小于右子树键的父节点和其左节点
依然要注意,size(x),返回的是x所有子节点的键,包括左和右,要找到x在树里排名要返回其左子树节点数