/** * 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: typedef long long ll; vector<ll>p; bool check() { int flag = 1; int len = p.size(); for (int i = 0; i < len-1; i++) { if (p[i] >= p[i + 1]) { flag = 0; break; } } return flag; } void Inorder(TreeNode* root) { if (root->left != NULL) //输出左节点 Inorder(root->left); p.push_back(root->val); if (root->right != NULL) Inorder(root->right);//输出右节点 } bool isValidBST(TreeNode* root) { if (root == NULL) return true; Inorder(root); return check(); } };
class Solution { public: typedef long long ll; //如果左子树的最大值比根节点大,或者右子树的最小值比根节点小,就不是二叉搜索树 bool check(TreeNode* root,ll lower,ll upper) { if (root == NULL) return true; if (root->val <= lower || root->val >= upper) return false; return check(root->left, lower, root->val) && check(root->right, root->val, upper); } bool isValidBST(TreeNode* root) { //LONG_MIN和LONG_MAX分别是系统可以提供的最小值和最大值,可以理解为负无穷和正无穷 return check(root, LONG_MIN, LONG_MAX); } };
原文:https://www.cnblogs.com/-citywall123/p/12843749.html