代码
/**
* 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) return true;
return dfs(root)[0];
}
vector<int> dfs(TreeNode* root) {
vector<int> ans({1, root->val, root->val});
if (root->left) {
auto t = dfs(root->left);
if (!t[0] || t[2] >= root->val) ans[0] = 0;
ans[1] = min(ans[1], t[1]);
ans[2] = max(ans[2], t[2]);
}
if (root->right) {
auto t = dfs(root->right);
if (!t[0] || t[1] <= root->val) ans[0]= 0;
ans[1] = min(ans[1], t[1]);
ans[2] = max(ans[2], t[2]);
}
return ans;
}
};