我将 Sedgewick 的名为 Algorithms 的书中的代码作为一种形式:
private Node deleteMin(Node x) {
if (x.left == null) return x.right;
x.left = deleteMin(x.left);
x.N = size(x.left) + size(x.right) + 1;
return x;
}
public void delete(Key key) {
root = delete(root, key);
}
private Node delete(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp < 0) x.left = delete(x.left, key);
else if (cmp > 0) x.right = delete(x.right, key);
else {
if (x.right == null) return x.left;
if (x.left == null) return x.right;
Node t = x;
x = min(t.right);
x.right = deleteMin(t.right);
x.left = t.left;
}
x.N = size(x.left) + size(x.right) + 1;
return x;
}
基本上我想知道递归在树中是如何工作的,因为我想将此方法转换为在找到节点时将其旋转直到变成叶子然后删除它。
public void delete(Key key) {
root = delete(root, key);
}
private Node delete(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp < 0) x.left = delete(x.left, key);
else if (cmp > 0) x.right = delete(x.right, key);
else {
//if is a leaf delete it
//if has one child rotate it
//if it has two children compare some value
//of the children choose the bigger and rotate
}
x.N = size(x.left) + size(x.right) + 1;
return x;
}
private Node rotateLeft(Node h)
{
Node x = h.right;
h.right = x.left;
x.left = h;
return x;
}
private Node rotateRight(Node h)
{
Node x = h.left;
h.left = x.right;
x.right = h;
return x;
}
我尝试了一些东西,但它抛出了一个空指针异常。我已经设法迭代地做到了,但是指向节点的指针没有更新,所以我丢失了树。有人可以告诉我它是如何工作的,以便我可以正确修改它吗?