Skip to content

Commit 5f15637

Browse files
committed
Fixed Validate BST
Note that the original implementation will cause wrong answer. The new version I updated is correct.
1 parent d4ee008 commit 5f15637

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

C++/chapTree.tex

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1451,17 +1451,27 @@ \subsubsection{代码}
14511451
// 时间复杂度O(n),空间复杂度O(\logn)
14521452
class Solution {
14531453
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);
14641465
}
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;
14651475
};
14661476
\end{Code}
14671477

0 commit comments

Comments
 (0)