原题
https://leetcode.cn/problems/validate-binary-search-tree/description/
思路
递归
复杂度
时间:O(n)
空间:O(n)
Python代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def isBST(root, left = float('-inf'), right = float('inf')):
if not root:
return True
if left >= root.val or right <= root.val:
return False
if not isBST(root.left, left, root.val):
return False
if not isBST(root.right, root.val, right):
return False
return True
return isBST(root)
Go代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isValidBST(root *TreeNode) bool {
// 匿名函数
var isBST func(*TreeNode, int, int) bool
isBST = func(root *TreeNode, left int, right int) bool {
if root == nil {
return true
}
if left >= root.Val || right <= root.Val {
return false
}
if isBST(root.Left, left, root.Val) == false {
return false
}
if isBST(root.Right, root.Val, right) == false {
return false
}
return true
}
return isBST(root, math.MinInt32-1, math.MaxInt32+1)
}
391

被折叠的 条评论
为什么被折叠?



