/** * 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(
/** * 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); } 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); } };
1LL是long long 类型的1,一个int 型的数和一个long long 型的数做运算返回值是long long 类型的,利用这种方式来防止溢出。
std::to_string() 是c++11引入的函数,其使用方法如下:
string to_string (int val); string to_string (long val); string to_string (long long val); string to_string (unsigned val); string to_string (unsigned long val); string to_string (unsigned long long val); string to_string (float val); string to_string (double val); string to_string (long double val);
样例如下:
// to_string example #include <iostream> // std::cout #include <string> // std::string, std::to_string int main () { std::string pi = "pi is " + std::to_string(3.1415926); std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number"; std::cout << pi << '\n'; std::cout << perfect << '\n'; return 0; }
Output:
pi is 3.141593 28 is a perfect number
但std::to_string()无法控制生成字符串的格式,意味着你会遇见这样的情况:
std::cout << std::to_string(0.33) << std::endl; 0.330000