-
Notifications
You must be signed in to change notification settings - Fork 1
/
bst.go
46 lines (42 loc) · 952 Bytes
/
bst.go
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
package bst
import "github.com/catorpilor/leetcode/utils"
func insertIntoBST(root *utils.TreeNode, val int) *utils.TreeNode {
return helper(root, val)
}
// helper is a recursive approach. tiem complexity O(N), space complexity O(lgN)
func helper(root *utils.TreeNode, val int) *utils.TreeNode {
if root == nil {
return &utils.TreeNode{Val: val}
}
if root.Val < val {
root.Right = helper(root.Right, val)
} else {
root.Left = helper(root.Left, val)
}
return root
}
// useIter time complexity O(N), space complexity O(1)
func useIter(root *utils.TreeNode, val int) *utils.TreeNode {
cur := root
if cur == nil {
return &utils.TreeNode{Val: val}
}
for {
if val > cur.Val {
if cur.Right == nil {
cur.Right = &utils.TreeNode{Val: val}
break
} else {
cur = cur.Right
}
} else {
if cur.Left == nil {
cur.Left = &utils.TreeNode{Val: val}
break
} else {
cur = cur.Left
}
}
}
return root
}