private val nodes = mutableListOf<Int>()
fun increasingBST(root: TreeNode?): TreeNode? {
if (root == null) return null
inorder(root)
val newRoot = TreeNode(nodes[0])
var current = newRoot
for (i in 1 until nodes.size) {
current.right = TreeNode(nodes[i])
current = current.right
}
return newRoot
}
private fun inorder(root: TreeNode?) {
if (root == null) return
inorder(root.left)
nodes.add(root.`val`)
inorder(root.right)
}- Time Complexity:
O(n). - Space Complexity:
O(n).