java来自维基百科的左树形代码正确吗?
public Node merge(Node x, Node y) {
if(x == null)
return y;
if(y == null)
return x;
// if this was a max height biased leftist tree, then the
// next line would be: if(x.element < y.element)
if(x.element.compareTo(y.element) > 0) {
// x.element > y.element
Node temp = x;
x = y;
y = temp;
}
x.rightChild = merge(x.rightChild, y);
if(x.leftChild == null) {
// left child doesn't exist, so move right child to the left side
x.leftChild = x.rightChild;
x.rightChild = null;
x.s = 1;
} else {
// left child does exist, so compare s-values
if(x.leftChild.s < x.rightChild.s) {
Node temp = x.leftChild;
x.leftChild = x.rightChild;
x.rightChild = temp;
}
// since we know the right child has the lower s-value, we can just
// add one to its s-value
x.s = x.rightChild.s + 1;
}
return x;
}
让我问这个问题的是:
if(x.element.compareTo(y.element) > 0) {
// x.element > y.element
Node temp = x;
x = y;
y = temp;
}
这不是行不通吗,因为引用只在方法内部切换
# 1 楼答案
方法的其余部分将对切换的引用进行操作,这使得切换非常有意义
# 2 楼答案
它切换它们是为了在方法内部执行后续操作。尽管开关不会直接改变方法之外的任何引用,但检查是这样做的,这样代码中只有一条逻辑路径,值较小的元素总是在x节点中,这样它们在代码中稍后的交换可以与正确的元素一起工作
对于一个特定的例子,请看下一行代码:
两个(x或y)中较小的一个将在它下面合并,在它的右边,两个中较大的一个。因此,这允许方法本身考虑顺序,这意味着这两个元素可以按任意顺序添加,因此会出现正确的行为
希望这有帮助