LeetCode 98. Validate Binary Search Tree
原题链接
中等
C++ 代码
/**
* 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) {
return dfs(root,INT_MIN,INT_MAX); //INT_MAX = 2^31 - 1 =2147483647
//INT_MIN= - 2^31 = -2147483648
}
bool dfs(TreeNode* root, long long minv, long long maxv)
{
if (!root) return true;
if (root->val<minv||root->val>maxv) return false;
return dfs(root->left,minv,root->val-1ll)&&dfs(root->right,root->val+1ll,maxv);
//LL代表long long, * 1LL是为了在计算时,把int类型的变量转化为long long,然后再赋值给longlong类型的变量
}
};