给定一个二叉树根节点,请你判断这棵树是不是二叉搜索树。
二叉搜索树满足每个节点的左子树上的所有节点均严格小于当前节点且右子树上的所有节点均严格大于当前节点。
- /**
- * struct TreeNode {
- * int val;
- * struct TreeNode *left;
- * struct TreeNode *right;
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * };
- */
- class Solution {
- public:
- /**
- * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
- *
- *
- * @param root TreeNode类
- * @return bool布尔型
- */
- int min=INT_MIN;
- bool isValidBST(TreeNode* root) {
- // write code here
- if(root==nullptr)return true;
- if(!isValidBST(root->left)){
- return false;
- }
- if(min>=root->val){
- return false;
- }else{
- min=root->val;
- }
- if(!isValidBST(root->right)){
- return false;
- }
- return true;
- }
- };
- /**
- * struct TreeNode {
- * int val;
- * struct TreeNode *left;
- * struct TreeNode *right;
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * };
- */
- class Solution {
- public:
- /**
- * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
- *
- *
- * @param root TreeNode类
- * @return bool布尔型
- */
- bool isValidBST(TreeNode* root) {
- // write code here
- stack
s; - TreeNode* cur=root;
- TreeNode* last=nullptr;
- while(cur || !s.empty()){
- if(cur){
- s.push(cur);
- cur=cur->left;
- }else{
- cur=s.top();
- s.pop();
- if(last){
- if(cur->val<=last->val){
- return false;
- }
- }
- last=cur;
- cur=cur->right;
- }
- }
- return true;
- }
- };