Files
hello-algo/en/codes/kotlin/chapter_tree/binary_tree.kt
Yudong Jin 14c314c08c Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
2026-10-31 03:35:51 +08:00

40 lines
880 B
Kotlin

/**
* File: binary_tree.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_tree
import utils.TreeNode
import utils.printTree
/* Driver code */
fun main() {
/* Initialize the binary tree */
// Initialize the nodes
val n1 = TreeNode(1)
val n2 = TreeNode(2)
val n3 = TreeNode(3)
val n4 = TreeNode(4)
val n5 = TreeNode(5)
// Set up references (pointers) between the nodes
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
println("\nInitialize the binary tree\n")
printTree(n1)
/* Insert and remove nodes */
val P = TreeNode(0)
// Insert node P between n1 and n2 in n1 -> n2
n1.left = P
P.left = n2
println("\nAfter inserting node P:\n")
printTree(n1)
// Remove node P
n1.left = n2
println("\nAfter removing node P:\n")
printTree(n1)
}