上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* 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)
}