【发布时间】:2017-01-13 06:10:41
【问题描述】:
这是来自互联网的关于 Red-Black BST Java 实现的算法。我对这个程序中名为 val 的变量感到困惑。代码如下:
package tools;
public class redBlack2 {
private static final boolean RED = true;
private static final boolean BLACK = false;
private Node root;
public redBlack2() {}
private class Node {
private int key;
private int val;
private Node left, right;
private boolean color;
public Node(int key, int val, boolean color) {
this.key = key;
this.val = val;
this.color = color;
}
}
private boolean isRed(Node x) {
if (x == null) return false;
return x.color == RED;
}
public int get(int key) {
return get(root, key);
}
private int get(Node x, int key) {
while (x != null) {
if (key < x.key) x = x.left;
else if (key > x.key) x = x.right;
else return x.val;
}
System.out.println("There is no such key.");
return 0;
}
public boolean contains(int key) {
return get(key) != 0;
}
public void put(int key, int val) {
root = put(root, key, val);
root.color = BLACK;
}
private Node put(Node h, int key, int val) {
if (h == null) return new Node(key, val, RED);
if (key<h.key) h.left = put(h.left, key, val);
else if (key>h.key) h.right = put(h.right, key, val);
else if (key == h.key) h.val = val;
if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
if (isRed(h.left) && isRed(h.right)) flipColors(h);
return h;
}
private Node rotateRight(Node h) {
Node x = h.left;
h.left = x.right;
x.right = h;
x.color = x.right.color;
x.right.color = RED;
return x;
}
private Node rotateLeft(Node h) {
Node x = h.right;
h.right = x.left;
x.left = h;
x.color = x.left.color;
x.left.color = RED;
return x;
}
private void flipColors(Node h) {
h.color = !h.color;
h.left.color = !h.left.color;
h.right.color = !h.right.color;
}
public static void main(String[] args) {
redBlack2 r = new redBlack2();
r.put(34,1);
r.put(23,2);
r.put(65,3);
r.put(73, 4);
System.out.print(r.get(73));
}
}
这只是我们对放入树中的数字的标记吗?那么我们不是已经有钥匙作为标记了吗?为什么我们还需要变量val?
【问题讨论】:
-
假设有人给你一本你从未见过的字典。你决定查一个词。当你找到这个词时,字典不会告诉你任何关于它的信息——没有发音,没有定义,没有任何东西,只有这个词。你不知道比以前更多(除了你知道这个词在字典里,这是一点点,但不多)。拥有一本能提供更多信息的词典不是更有用吗?这是否有助于解释
val的用途? -
val存储在对put(int key, int val)的调用中给出的值,然后由get(int key)返回。为什么你认为key的值与val的值相同?如果你只是简单地按照代码来查看值的来源和使用位置,答案就是这样。 -
同样,Java 提供
Set和Map集合。Set可以查找密钥并告诉您该密钥是否在集合中,但它不能告诉您更多信息。Map允许您提供与密钥关联的其他数据。这有助于解释吗?
标签: java algorithm binary-search-tree red-black-tree