https://leetcode.com/submissions/detail/39976412/
//2015-10-22 20:58:42
//1.中序 保存在一个vector中,检查是否有序
//2.传递前驱指针,看是否有序
//3.从底向上 ,开始只传递回最大值,不对,比如右侧应该传回最小值,因此改为两个返回值
//2015-10-22 21:24:21
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root == NULL){
return true;
}
int leftmin,rightmax = 0;
return check(root,leftmin,rightmax);
}
bool check(TreeNode *root,int &leftmin,int &rightmax){
if(root == NULL){
return true;
}
leftmin = root->val;
rightmax = root->val;
if(root->left==NULL &&root->right==NULL){
return true;
}
int left,right;
if(root->left != NULL){
if(check(root->left,left,right) == false || right>=root->val){
return false;
}
leftmin = left;
}
if(root->right != NULL){
if(check(root->right,left,right)==false || left<=root->val){
return false;
}
rightmax = right;
}
return true;
}
};
另外,还有一种是从顶向下的递归方法,每次把两个边界传递过来,初始值有问题,例如设为INT_MIN 或INT_MAX,如果测试用例中包含该值则出错。