Skip to content

Latest commit

 

History

History
28 lines (24 loc) · 697 Bytes

File metadata and controls

28 lines (24 loc) · 697 Bytes

Inorder Traversal

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).