-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinsert_into_a_binary_search_tree.go
More file actions
61 lines (55 loc) · 1.19 KB
/
Copy pathinsert_into_a_binary_search_tree.go
File metadata and controls
61 lines (55 loc) · 1.19 KB
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
58
59
60
61
package leetcode
// Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// iterative solution
// Time complexity: O(log n) for a balanced tree, otherwise O(n)
// Space complexity: O(1)
func insertIntoBST(root *TreeNode, val int) *TreeNode {
if root == nil {
node := TreeNode{val, nil, nil}
return &node
}
curr := root
for true {
if val < curr.Val {
if curr.Left == nil {
node := TreeNode{val, nil, nil}
curr.Left = &node
break
} else {
curr = curr.Left
}
} else {
if curr.Right == nil {
node := TreeNode{val, nil, nil}
curr.Right = &node
break
} else {
curr = curr.Right
}
}
}
return root
}
// recursive solution
// Time complexity: O(log n) for a balanced tree, otherwise O(n)
// Space complexity: O(log n) for the stack in a balanced tree, otherwise O(n)
func insertIntoBST2(root *TreeNode, val int) *TreeNode {
return insert(root, val)
}
func insert(node *TreeNode, val int) *TreeNode {
if node == nil {
newNode := TreeNode{val, nil, nil}
return &newNode
}
if val < node.Val {
node.Left = insert(node.Left, val)
} else {
node.Right = insert(node.Right, val)
}
return node
}