-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path0701-insert-into-a-binary-search-tree.kt
57 lines (46 loc) · 1.36 KB
/
0701-insert-into-a-binary-search-tree.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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`
}