代码随想录:验证二叉搜索树

二叉搜索树的中序遍历结果是一个递增的数组

为了省空间可以用一个变量记录上一次的数字

我一开始设置上一次的为null,结果c++中int为null时实际为0,所以要用最小值

/**
 * 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:
    long long last = LLONG_MIN;
    bool isValidBST(TreeNode* root) {
        if (root == NULL)
            return true;

        bool left = isValidBST(root->left);

        if (last >= root->val) {
            return false;
        }
        last = root->val;

        bool right = isValidBST(root->right);

        return left && right;
    }
};
posted @ 2025-01-16 20:01  huigugu  阅读(9)  评论(0)    收藏  举报