题解 | #判断是不是二叉搜索树#

判断是不是二叉搜索树

https://www.nowcoder.com/practice/a69242b39baf45dea217815c7dedb52b

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <variant>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return bool布尔型
     */
    struct Inf {};
    using Bound = std::variant<int, Inf>;
    using Range = std::pair<Bound, Bound>;
    bool isValidBST(TreeNode* root) {
        Inf inf;
        auto isInRange = [](const Range& r, auto val) -> bool {
            const auto& [lb, ub] = r;
            bool res = true;
            if(lb.index() == 0) res &= std::get<0>(lb) < val;
            if(ub.index() == 0) res &= val < std::get<0>(ub);
            return res;
        };
        auto check = [&inf, &isInRange](auto&& self, TreeNode* n, Range r) -> bool {
            if (not n) return true;
            const auto& [lb, ub] = r;
            bool res = true;
            res &= self(self, n->left, {lb, n->val});
            res &= self(self, n->right, {n->val, ub});
            return res & isInRange(r, n->val);
        };
        
        return check(check, root, {inf, inf});
    }
};

全部评论

相关推荐

冰皮月饼_FLORRIEEE:你是准备投产品嘛?可以重新整理一下实习的bulletpoint,侧重描述你的工作所带来的结果收益,不要只写泛泛的内容(比如改写通过xx数据分析,提升xx),产品的价值并不在处理和分析数据的过程
点赞 评论 收藏
分享
这一生如履薄冰:美赛s就别写了吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务