另外一个思路是采用中序遍历,保存last 指针,判断 last 指针是否小于当前值
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isValidBST(root *TreeNode) bool {
return isValid(root, -1<<63, 1<<63 - 1)
}
func isValid(root *TreeNode, min, max int) bool {
if root == nil {
return true
}
if root.Val <= min {
return false
}
if root.Val >= max {
return false
}
return isValid(root.Left, min, root.Val) && isValid(root.Right, root.Val, max)
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isValidBST(root *TreeNode) bool {
inorder := inOrder(root)
for i:=1;i<len(inorder) ;i++ {
if inorder[i-1] >= inorder[i] {
return false
}
}
return true
}
func inOrder(root *TreeNode) []int {
if root == nil {
return []int{}
}
return append(append(inOrder(root.Left), root.Val), inOrder(root.Right)...)
}