struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
//hint: when involved with BST, always remember that special effect of in-order traversal
//1. pass down the low and high limits from node to node
//2. we can always do an in-order traversal of BST, then the value we visited should be in increasing order,
//so we can check the previous is smaller than current value
public:
bool isBSTHelper(TreeNode* root, int low, int high)
{
if(!root)
return true;
if (low < root->val && high > root->val)
return isBSTHelper(root->left, low, root->val)
&& isBSTHelper(root->right, root->val, high);
else return false;
}
bool isBSTHelper(TreeNode* root, int& prev)
{
if(!root)
return true;
return isBSTHelper(root->left, prev) && (root->val > prev)
&& ((prev = root->val)||true) && isBSTHelper(root->right, prev);
}
bool isValidBST(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//first solution
//return isBSTHelper(root, INT_MIN, INT_MAX);
//second solution
int prev = INT_MIN;
return isBSTHelper(root, prev);
}
};
second time
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBSTUtil(TreeNode* root, int mmin, int mmax)
{
if(root == NULL) return true;
if(mmin < root->val && root->val < mmax)
{
return isValidBSTUtil(root->left, mmin, min(mmax, root->val))
&& isValidBSTUtil(root->right, max(mmin, root->val), mmax);
}
else return false;
}
bool isValidBST(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int mmin = INT_MIN;
int mmax = INT_MAX;
return isValidBSTUtil(root, mmin, mmax);
}
};
本文介绍了一种通过中序遍历来判断C++二叉搜索树有效性的算法,详细解释了如何利用中序遍历的有序性质来验证二叉搜索树的正确性。
276

被折叠的 条评论
为什么被折叠?



