-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (70 loc) · 1.47 KB
/
main.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
// Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// recursive inorder traversal
// time complexity: O(n)
// space complexity: O(n)
func isValidBST(root *TreeNode) bool {
var nums []int
var dfs func(*TreeNode)
dfs = func(node *TreeNode) {
if node != nil {
dfs(node.Left)
nums = append(nums, node.Val)
dfs(node.Right)
}
}
dfs(root)
if len(nums) == 0 {
return true
}
prev := nums[0]
for i := 1; i < len(nums); i++ {
if nums[i] <= prev {
return false
}
prev = nums[i]
}
return true
}
// recursive traversal with valid range
// time complexity: O(n)
// space complexity: O(n)
func isValidBST2(root *TreeNode) bool {
var validate func(*TreeNode, int, int) bool
validate = func(node *TreeNode, low, high int) bool {
if node == nil {
return true
}
if low >= node.Val || high <= node.Val {
return false
}
return validate(node.Left, low, node.Val) && validate(node.Right, node.Val, high)
}
return validate(root, -(1<<31 + 1), 1<<31)
}
// iterative inorder traversal
// time complexity: O(n)
// space complexity: O(n)
func isValidBST3(root *TreeNode) bool {
var stack []*TreeNode
prev := -(1<<31 + 1)
for len(stack) > 0 || root != nil {
for root != nil {
stack = append(stack, root)
root = root.Left
}
root = stack[len(stack)-1]
stack = stack[:len(stack)-1]
if root.Val <= prev {
return false
}
prev = root.Val
root = root.Right
}
return true
}