2010-05-06 51 views
1

Link这是左派树从维基百科的一段代码是否正确?

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; 
    } 

是不是只是不是要去工作,因为引用只在方法内部交换?

+0

那当然不是*对*。 – David 2010-05-06 20:40:53

+0

左边的树?我不知道数据结构已经变得政治化了。在我们的社会中安全吗? – duffymo 2010-05-06 22:29:09

回答

1

它正在将它们切换为方法内部稍后执行的目的。虽然交换机不直接在方法外改变任何引用,但检查完成后,代码中只有一条逻辑路径,小值元素始终位于x节点中,以便稍后在代码中进行交换与正确的元素一起工作。

对于一个具体的例子,看的下一行代码:

x.rightChild = merge(x.rightChild, y); 

无论是两个(X或Y)将被合并在其下方的小,在它的右子节点,较大他们俩。所以,这允许方法本身担心排序,并且意味着可以以任何顺序添加这两个元素,并且因为它会发生正确的行为。

希望这会有所帮助。

0

这不就是不会工作,因为 的参考文献只是切换 里面的方法?

该方法的其余部分将对交换引用进行操作,使交换机非常有意义。