驗證二叉搜索樹
利用中序遍歷的性質(中序即升序)。
/**
* 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:
vector<int> res;
bool isValidBST(TreeNode* root) {
inOrder(root);
for(int i=1;i<res.size();i++){
if(res[i]<=res[i-1]){
return false;
}
}
return true;
}
void inOrder(TreeNode *root){
if(!root){
return ;
}
inOrder(root->left);
res.push_back(root->val);
inOrder(root->right);
}
};
遞歸版:
(要開long long)
/**
* 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 check(root,LLONG_MIN,LLONG_MAX);
}
bool check(TreeNode *root,long long min,long long max){
if(!root){
return true;
}
if(root->val<=min || root->val>=max){
return false;
}
if(check(root->left,min,root->val) &&
check(root->right,root->val,max) ){
return true;
}
return false;
}
};