98. 验证二叉搜索树(LeetCode)(中序遍历dfs)

98. 验证二叉搜索树
中序遍历

/**
 * 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 x;
    bool dfs(struct TreeNode* root){
        if(root == NULL) return true;
        if(dfs(root->left)){
            if(x < root->val){
                x = root->val;
                if(dfs(root->right)){
                    return true;
                }
            }
        }

        return false;
    }
    bool isValidBST(TreeNode* root) {
        x = -2147483649;
        return dfs(root);
    }


};

按照二叉搜索树定义

/**
 * 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) {
        return dfs(root)[0];
    }

    vector<int> dfs(TreeNode* root){
        //存储是否符合条件,最小值,最大值
        vector<int> res = {1, root->val, root->val};
        if(root->left){
            auto t = dfs(root->left);
            if(!t[0] || t[2] >= root->val) res[0] = 0;
            res[1] = min(res[1], t[1]);
            res[2] = max(res[2], t[2]);
        }
        if(root->right){
            auto t = dfs(root->right);
            if(!t[0] || t[1] <= root->val) res[0] = 0;
            res[1] = min(res[1], t[1]);
            res[2] = max(res[2], t[2]);
        }
        return res;
    }   

};
posted @ 2025-03-12 11:38  awei040519  阅读(16)  评论(0)    收藏  举报