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
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type Result struct {
isValid bool
minVal int
maxVal int
}
func isValidBST(root *TreeNode) bool {
if root == nil {
return true
}
var dfs func(root *TreeNode) *Result
dfs = func(root *TreeNode) *Result {
ret := &Result{}
if root.Left == nil && root.Right == nil {
ret.isValid, ret.minVal, ret.maxVal = true, root.Val, root.Val
} else if root.Left == nil {
// root.Right != nil
rightRes := dfs(root.Right)
if rightRes.isValid && rightRes.minVal > root.Val {
ret.isValid, ret.minVal, ret.maxVal = true, root.Val, rightRes.maxVal
}
} else if root.Right == nil {
// root.Left != nil
leftRes := dfs(root.Left)
if leftRes.isValid && leftRes.maxVal < root.Val {
ret.isValid, ret.minVal, ret.maxVal = true, leftRes.minVal, root.Val
}
} else {
// root.Left != nil && root.Right != nil
leftRes := dfs(root.Left)
rightRes := dfs(root.Right)
if leftRes.isValid && rightRes.isValid && leftRes.maxVal < root.Val && rightRes.minVal > root.Val {
ret.isValid, ret.minVal, ret.maxVal = true, leftRes.minVal, rightRes.maxVal
}
}
return ret
}
res := dfs(root)
return res.isValid
}
|