File tree Expand file tree Collapse file tree 1 file changed +20
-10
lines changed Expand file tree Collapse file tree 1 file changed +20
-10
lines changed Original file line number Diff line number Diff line change @@ -1451,17 +1451,27 @@ \subsubsection{代码}
1451
1451
// 时间复杂度O(n),空间复杂度O(\logn )
1452
1452
class Solution {
1453
1453
public:
1454
- bool isValidBST(TreeNode* root) {
1455
- return isValidBST(root, INT_MIN, INT_MAX);
1456
- }
1457
-
1458
- bool isValidBST(TreeNode* root, int lower, int upper) {
1459
- if (root == nullptr) return true;
1460
-
1461
- return root->val > lower && root->val < upper
1462
- && isValidBST(root->left, lower, root->val)
1463
- && isValidBST(root->right, root->val, upper);
1454
+ bool isValidBST(TreeNode * root) {
1455
+ inorder(root);
1456
+ return is_sorted(values.begin(), values.end(), cmp());
1457
+ }
1458
+
1459
+ void inorder(TreeNode * root) {
1460
+ if(!root)
1461
+ return;
1462
+ inorder(root->left);
1463
+ values.push_back(root->val);
1464
+ inorder(root->right);
1464
1465
}
1466
+
1467
+ private:
1468
+ struct cmp {
1469
+ bool operator()(const int & first, const int & second) {
1470
+ return first <= second;
1471
+ }
1472
+ };
1473
+
1474
+ vector<int> values;
1465
1475
};
1466
1476
\end {Code }
1467
1477
You can’t perform that action at this time.
0 commit comments