您的位置:首页 > 其它

[LeetCode]Validate Binary Search Tree

2013-06-03 09:09 260 查看
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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: