列表

详情


98. 验证二叉搜索树

给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。

有效 二叉搜索树定义如下:

 

示例 1:

输入:root = [2,1,3]
输出:true

示例 2:

输入:root = [5,1,4,null,null,3,6]
输出:false
解释:根节点的值是 5 ,但是右子节点的值是 4 。

 

提示:

相似题目

二叉树的中序遍历

二叉搜索树中的众数

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { } };

python3 解法, 执行用时: 48 ms, 内存消耗: 17.5 MB, 提交时间: 2022-07-14 14:21:33

# 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:
        _min, _max = -2**32, 2**32
        return self.helper(root, _min, _max)


    def helper(self, node: TreeNode, _min: int, _max: int) -> bool:
        if node is None:
            return True
        if node.val >= _max or node.val <= _min:
            return False
            
        return self.helper(node.left, _min, node.val) and self.helper(node.right, node.val, _max)

golang 解法, 执行用时: 0 ms, 内存消耗: 5.1 MB, 提交时间: 2021-07-26 14:39:10

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isValidBST(root *TreeNode) bool {
    min, max := math.MinInt64, math.MaxInt64
    return helper(root, min, max)
}

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

上一题