98. 验证二叉搜索树

image.png
image.png

  1. type TreeNode struct {
  2. Val int
  3. Left *TreeNode
  4. Right *TreeNode
  5. }
  6. func isValidBST(root *TreeNode) bool {
  7. if root==nil{
  8. return true
  9. }
  10. stack := make([]*TreeNode,0)
  11. preVal :=math.MinInt64
  12. for root!=nil||len(stack)>0{
  13. for root!=nil{
  14. stack = append(stack,root)
  15. root =root.Left
  16. }
  17. node := stack[len(stack)-1]
  18. stack =stack[:len(stack)-1]
  19. if node.Val<=preVal {
  20. return false
  21. }
  22. preVal = node.Val
  23. root =node.Right
  24. }

image.png

递归

func isValidBST(root *TreeNode) bool {
    if root==nil{
        return true
    }
    return helper(root,math.MinInt64,math.MaxInt64)
}

func helper(root *TreeNode,left,right int)bool{
    if root==nil{
        return true
    }
    if root.Val<=left||root.Val>=right{
        return false
    }
    return helper(root.Left,left,root.Val)&&helper(root.Right,root.Val,right)
}

image.png