# 98. 验证二叉搜索树

xiaoxiao2021-03-01  6

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { return valid(root, LONG_MIN, LONG_MAX); } bool valid(TreeNode* root, long minVal, long maxVal) { if(!root) return true; if(root->val <= minVal || root->val >= maxVal) { return false; } return valid(root->left, minVal, root->val) && valid(root->right, root->val, maxVal); } };

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { if(!root) { return true; } vector<int> res; inorder(root, res); for(int i = 0; i < res.size() - 1; i++) { if(res[i] >= res[i + 1]) { return false; } } return true; } void inorder(TreeNode* root, vector<int>& res) { if(!root) { return; } inorder(root->left, res); res.push_back(root->val); inorder(root->right, res); } };