验证二叉搜索树

2020-05-05  本文已影响0人  7赢月

题目描述

https://leetcode-cn.com/problems/validate-binary-search-tree/


package main

// 中序遍历
func isValidBST(root *TreeNode) bool {
    if root == nil {
        return true
    }
    var r []int
    if !isValidBSTDFS(root, &r) {
        return false
    }

    return true
}
func isValidBSTDFS(root *TreeNode, r *[]int) bool {
    if root == nil {
        return true
    }
    if !isValidBSTDFS(root.Left, r) {
        return false
    }
    if len(*r) != 0 && (*r)[len(*r)-1] >= root.Val {
        return false
    }
    *r = append(*r, root.Val)
    if !isValidBSTDFS(root.Right, r) {
        return false
    }
    return true
}

思路

使用中序遍历,就是递增数组!

上一篇 下一篇

猜你喜欢

热点阅读