Skip to content

Commit 5a6ed05

Browse files
authored
Create 0701-insert-into-a-binary-search-tree.kt
1 parent b8caf8a commit 5a6ed05

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* Example:
3+
* var ti = TreeNode(5)
4+
* var v = ti.`val`
5+
* Definition for a binary tree node.
6+
* class TreeNode(var `val`: Int) {
7+
* var left: TreeNode? = null
8+
* var right: TreeNode? = null
9+
* }
10+
*/
11+
12+
// Recursive solution (Non self balancing)
13+
class Solution {
14+
fun insertIntoBST(root: TreeNode?, value: Int): TreeNode? {
15+
16+
root?: return TreeNode(value)
17+
18+
if (value > root.value) root.right = insertIntoBST(root.right, value)
19+
else root.left = insertIntoBST(root.left, value)
20+
21+
return root
22+
}
23+
24+
private val TreeNode.value get() = `val`
25+
}
26+
27+
// Iterative Solution (Non self balancing)
28+
class Solution {
29+
fun insertIntoBST(root: TreeNode?, value: Int): TreeNode? {
30+
31+
root?: return TreeNode(value)
32+
33+
var current = root
34+
35+
while (current != null) {
36+
if (value > current!!.value) {
37+
if (current.right != null){
38+
current = current?.right
39+
} else {
40+
current.right = TreeNode(value)
41+
break
42+
}
43+
} else {
44+
if (current.left != null){
45+
current = current?.left
46+
} else {
47+
current.left = TreeNode(value)
48+
break
49+
}
50+
}
51+
}
52+
53+
return root
54+
}
55+
56+
private val TreeNode.value get() = `val`
57+
}

0 commit comments

Comments
 (0)