左子树的任意节点的值都比root小
右子树的任意节点的值都比root大
TAT怎么做。。。
递归的时候设置个上下界就好了。。。
左子树,更新上届
右子树,更新下界
/**
* 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 valid(TreeNode* root , int lower , int upper){
if (root == nullptr) return true;
return root -> val > lower && root -> val < upper && valid(root -> left , lower , root -> val) && valid(root -> right , root -> val , upper);
}
bool isValidBST(TreeNode *root) {
return valid(root , INT_MIN , INT_MAX);
}
};
-------2014/12/18------
没考虑root->val是INT_MAX或者INT_MIN的情况
/** * 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 v(TreeNode* root, long long minv, long long maxv) { if (root == nullptr) return true; if (root->val > minv && root->val < maxv) { return v(root->left, minv, root->val) && v(root->right, root->val, maxv); } else { return false; } } bool isValidBST(TreeNode *root) { return v(root, (long long)INT_MIN - 1, (long long)INT_MAX + 1); } };