解题思路:
分别验证root的左右子树是否是二叉树,同时,左子树的最大值要小于root->val,右子树的最小值要大于root->val。
在左右子树中,一直向root的左子树探索,就能得到其最小值,一直向右探索,就能得到其最大值。
/**
* 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 isLeftBST(root->left, root->val) && isRightBST(root->right, root->val);
}
bool isLeftBST(TreeNode* root, int n){
if(isValidBST(root)){
while(root){
if(root->val >= n) return false;
root = root->right;
}
return true;
}
else return false;
}
bool isRightBST(TreeNode* root, int n){
if(isValidBST(root)){
while(root){
if(root->val <= n) return false;
root = root->left;
}
return true;
}
else return false;
}
};