题目:验证二叉搜索树
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a34fa8e1afee8bb3172197761ee1d184.png)
解法一:
class Solution {
public:
bool checkValidBST(TreeNode* root, long max, long min) {
if(nullptr == root) return true;
if(nullptr != root->right && root->right->val <= root->val) return false;
if(nullptr != root->left && root->left->val >= root->val) return false;
if(min >= root->val || root->val>=max) return false;
return checkValidBST(root->left,root->val,min) && checkValidBST(root->right,max,root->val);
}
bool isValidBST(TreeNode* root){
return checkValidBST(root,LONG_MAX,LONG_MIN);
}
};
解法二:中序遍历过后存放在数组内,比较是否为升序排列
class Solution {
public:
vector<int> order;
void inorder(TreeNode* root){
if(nullptr == root) return;
inorder(root->left);
order.push_back(root->val);
inorder(root->right);
}
bool isValidBST(TreeNode* root){
inorder(root);
for(int i=1;i<order.size();++i){
if(order[i-1]>=order[i]) return false;
}
return true;
}
};
解法三:递归
class Solution {
public:
long prev = LONG_MIN;
bool isValidBST(TreeNode* root){
if(nullptr == root) return true;
bool res = isValidBST(root->left);
if(!res) return res;
if(prev < root->val){
prev= root->val;
}else{
return false;
}
return isValidBST(root->right);
}
};
解法四:使用栈中序遍历(迭代)
class Solution {
public:
bool isValidBST(TreeNode* root){
stack<TreeNode*> s;
TreeNode* curr = root;
long prev = LONG_MIN;
while(nullptr != curr || !s.empty()){
while(nullptr != curr){
s.push(curr);
curr = curr->left;
}
curr = s.top();
s.pop();
if(prev >= curr->val) return false;
prev = curr->val;
curr = curr->right;
}
return true;
}
};