u
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
package top100liked
|
||||
|
||||
// https://leetcode.cn/problems/validate-binary-search-tree/description/?envType=study-plan-v2&envId=top-100-liked
|
||||
|
||||
type TreeNode struct {
|
||||
Val int
|
||||
Left *TreeNode
|
||||
Right *TreeNode
|
||||
}
|
||||
|
||||
// AC, 但很慢
|
||||
// func inorderTraversal(root *TreeNode) []int {
|
||||
// if root == nil {
|
||||
// return []int{}
|
||||
// }
|
||||
// res := []int{}
|
||||
// if root.Left != nil {
|
||||
// res = append(res, inorderTraversal(root.Left)...)
|
||||
// }
|
||||
// res = append(res, root.Val)
|
||||
// if root.Right != nil {
|
||||
// res = append(res, inorderTraversal(root.Right)...)
|
||||
// }
|
||||
// return res
|
||||
// }
|
||||
|
||||
// func isValidBST(root *TreeNode) bool {
|
||||
// if root == nil {
|
||||
// return true
|
||||
// }
|
||||
// l := inorderTraversal(root)
|
||||
// if len(l) == 1 {
|
||||
// return true
|
||||
// }
|
||||
// for i, j := 0, 1; j < len(l); {
|
||||
// if l[i] >= l[j] {
|
||||
// return false
|
||||
// }
|
||||
|
||||
// i++
|
||||
// j++
|
||||
// }
|
||||
// return true
|
||||
// }
|
||||
|
||||
func isValidBST(root *TreeNode) bool {
|
||||
var prev *int
|
||||
var inorder func(node *TreeNode) bool
|
||||
inorder = func(node *TreeNode) bool {
|
||||
if node == nil {
|
||||
return true
|
||||
}
|
||||
if !inorder(node.Left) {
|
||||
return false
|
||||
}
|
||||
if prev != nil && *prev >= node.Val {
|
||||
return false
|
||||
}
|
||||
prev = &node.Val
|
||||
if !inorder(node.Right) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
return inorder(root)
|
||||
}
|
||||
Reference in New Issue
Block a user