Ich habe Rot-schwarz-Baum in Kotlin geschrieben. Fun insertFixup stellt Balance nach dem Einfügen neuer Element (z: Node? ist neues Element). Der Algorithmus des Baumabgleichs wird von here (Seiten 2-3) genommen. Das Problem ist, dass Kotlin erlaubt mir nichtz-z.parent und z.parent.parent neu zuzuweisen. Ich möchte z ein Zeiger sein. Die Frage ist, wie man Kotlin verstehen lässt, was ich von ihm will?Kotlin Funktionsparameter: Val kann nicht neu zugewiesen werden
class Node(key: Int) {...}
class BinarySearchTree {
var root: Node? = null
fun insert(newNode: Node) {...}
fun RotateLeft(x: Node?) {...}
fun RotateRight(x: Node?) {...}
fun insertFixup(z: Node?) {
var y: Node?
while (z?.parent?.color == "RED") {
if (z?.parent == z?.parent?.parent?.left) {
y = z?.parent?.parent?.right
if (y?.color == "RED") {
z?.parent?.color = "BLACK"
y?.color = "BLACK"
z?.parent?.parent?.color = "RED"
z = z?.parent?.parent
}
if (z == z?.parent?.right) {
z = z?.parent
RotateLeft(z)
z?.parent?.color = "BLACK"
z?.parent?.parent?.color = "RED"
RotateRight(z?.parent?.parent)
}
} else {
y = z?.parent?.parent?.left
if (y?.color == "RED") {
z?.parent?.color = "BLACK"
y?.color = "BLACK"
z?.parent?.parent?.color = "RED"
z = z?.parent?.parent
}
if (z != z?.parent?.left) {
z = z?.parent
RotateLeft(z)
z?.parent?.color = "BLACK"
z?.parent?.parent?.color = "RED"
RotateRight(z?.parent?.parent)
}
}
}
root?.color = "BLACK"
}
}
fun main(args: Array<String>) {
val bst = BinarySearchTree()
while (true) {
var newNode = Node(readLine()!!.toInt())
bst.insert(newNode)
bst.insertFixup(newNode)
}
}
UPD: Danke an alle! Alle Antworten waren hilfreich und ich habe die Lösung in Ihren Antworten gefunden.
Ein kleiner Hinweis: ich glaube, Sie stark den Code verbessern können, wenn Sie überprüfen, ob '' Z' null' ist oder nicht nur einmal am Anfang o f 'insertFixup'. Im Moment gibt es ein bisschen zu viel "?" Überall im Ort;) – voddan