bool recursion(struct TreeNode* root,long lower,long upper){ if(!root) return true; if(root->val <= lower || root->val >= upper) return false; return recursion(root->left,lower,root->val) && recursion(root->right,root->val,upper); } bool isValidBST(struct TreeNode* root){ return recursion(root,LONG_MIN,LONG_MAX); }
class Solution { public: bool isValidBST(TreeNode* root) { stack<TreeNode*> stack; long long inorder = (long long)INT_MIN - 1; while (!stack.empty() || root != nullptr) { while (root != nullptr) { stack.push(root); root = root -> left; } root = stack.top(); stack.pop(); // 如果中序遍历得到的节点的值小于等于前一个 inorder,说明不是二叉搜索树 if (root -> val <= inorder) { return false; } inorder = root -> val; root = root -> right; } return true; } };