File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments