Skip to content

Commit

Permalink
Create 0701-insert-into-a-binary-search-tree.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
a93a authored Feb 24, 2023
1 parent b8caf8a commit 5a6ed05
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions kotlin/0701-insert-into-a-binary-search-tree.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/

// Recursive solution (Non self balancing)
class Solution {
fun insertIntoBST(root: TreeNode?, value: Int): TreeNode? {

root?: return TreeNode(value)

if (value > root.value) root.right = insertIntoBST(root.right, value)
else root.left = insertIntoBST(root.left, value)

return root
}

private val TreeNode.value get() = `val`
}

// Iterative Solution (Non self balancing)
class Solution {
fun insertIntoBST(root: TreeNode?, value: Int): TreeNode? {

root?: return TreeNode(value)

var current = root

while (current != null) {
if (value > current!!.value) {
if (current.right != null){
current = current?.right
} else {
current.right = TreeNode(value)
break
}
} else {
if (current.left != null){
current = current?.left
} else {
current.left = TreeNode(value)
break
}
}
}

return root
}

private val TreeNode.value get() = `val`
}

0 comments on commit 5a6ed05

Please sign in to comment.