实现一个函数,检查一棵二叉树是否为二叉搜索树。
/**
* 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:
long last = LONG_MIN;
bool isValidBST(TreeNode* root) {
if(root == NULL)
return true;
if(!isValidBST(root->left))
return false;
if(last >= root->val)
return false;
last = root->val;
if(!isValidBST(root->right))
return false;
return true;
}
};
/**
* 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,LONG_MIN,LONG_MAX);
}
bool check(TreeNode* root,long min,long max)
{
if(root == NULL)
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 false;
return true;
}
};