From 5f156379a5aa1a8686b7536ebc4d52b243f16f5f Mon Sep 17 00:00:00 2001 From: Xieyang Liu Date: Thu, 25 Feb 2016 00:26:39 -0500 Subject: [PATCH 1/2] Fixed Validate BST Note that the original implementation will cause wrong answer. The new version I updated is correct. --- C++/chapTree.tex | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/C++/chapTree.tex b/C++/chapTree.tex index 4a13b126..ec819ae3 100644 --- a/C++/chapTree.tex +++ b/C++/chapTree.tex @@ -1451,17 +1451,27 @@ \subsubsection{代码} // 时间复杂度O(n),空间复杂度O(\logn) class Solution { public: - bool isValidBST(TreeNode* root) { - return isValidBST(root, INT_MIN, INT_MAX); - } - - bool isValidBST(TreeNode* root, int lower, int upper) { - if (root == nullptr) return true; - - return root->val > lower && root->val < upper - && isValidBST(root->left, lower, root->val) - && isValidBST(root->right, root->val, upper); + bool isValidBST(TreeNode * root) { + inorder(root); + return is_sorted(values.begin(), values.end(), cmp()); + } + + void inorder(TreeNode * root) { + if(!root) + return; + inorder(root->left); + values.push_back(root->val); + inorder(root->right); } + +private: + struct cmp { + bool operator()(const int & first, const int & second) { + return first <= second; + } + }; + + vector values; }; \end{Code} From 678f159c0170672b93ad438d1de6fec465626cfe Mon Sep 17 00:00:00 2001 From: Xieyang Liu Date: Thu, 25 Feb 2016 00:29:40 -0500 Subject: [PATCH 2/2] Fix Validate BST MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 加了分析 --- C++/chapTree.tex | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/chapTree.tex b/C++/chapTree.tex index ec819ae3..4ac6728a 100644 --- a/C++/chapTree.tex +++ b/C++/chapTree.tex @@ -1442,12 +1442,13 @@ \subsubsection{描述} \subsubsection{分析} - +检查中序遍历得到的数列是否是递增数列。注意comparator的使用。 \subsubsection{代码} \begin{Code} // LeetCode, Validate Binary Search Tree +// @author Michael Liu (http://lxieyang.github.io) // 时间复杂度O(n),空间复杂度O(\logn) class Solution { public: