-
Notifications
You must be signed in to change notification settings - Fork 0
/
701.go
36 lines (30 loc) · 869 Bytes
/
701.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
// Name: Insert in a Binary Search Tree
// Tags: Binary Search Tree, recursion
// Stats: 16ms-97.70%, 7.2mb-99.65%
func insertIntoBST(root *TreeNode, val int) *TreeNode {
if root == nil { return &TreeNode{val, nil, nil} }
if val < root.Val {
root.Left = insertIntoBST(root.Left, val)
} else {
root.Right = insertIntoBST(root.Right, val)
}
return root
}
// Less clean, but slight faster (maybe?) version
func insertIntoBST(root *TreeNode, val int) *TreeNode {
if root == nil { return &TreeNode{val, nil, nil} }
if val < root.Val {
if root.Left == nil {
root.Left = &TreeNode{val, nil, nil}
} else {
insertIntoBST(root.Left, val)
}
} else {
if root.Right == nil {
root.Right = &TreeNode{val, nil, nil}
} else {
insertIntoBST(root.Right, val)
}
}
return root
}