题目
题解
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int getMin(struct TreeNode* root){
int min = root->val;
if(root->left != NULL){
min = getMin(root->left)<min? getMin(root->left):min;
}
//由于已经验证root是二叉搜索树,因此比较小值只可能存在左子树中
// if(root->right != NULL){
// min = getMin(root->right)<min? getMin(root->right):min;
// }
return min;
}
int getMax(struct TreeNode* root){
int max = root->val;
//由于已经验证root是二叉搜索树,因此比较大值只可能存在右子树中
// if(root->left != NULL){
// max = getMax(root->left)>max? getMax(root->left):max;
// }
if(root->right != NULL){
max = getMax(root->right)>max? getMax(root->right):max;
}
return max;
}
bool isValidBST(struct TreeNode* root){
if(root == NULL) return true;
if(isValidBST(root->left)&&isValidBST(root->right)){
int flag = 1;
//不能小于等于左边的最大值。
if(root->left != NULL){
if(root->val <= getMax(root->left)){
flag = 0;
}
}
//不能大于等于右边的最小值。
if(root->right != NULL){
if(root->val >= getMin(root->right)){
flag = 0;
}
}
if(flag == 1){
return true;
}
}
return false;
}
要点
验证二叉搜索树不像验证二叉平衡树那样两边子树都是获取高度(详见力扣刷题-110.平衡二叉树)。
二叉搜索树是在确认两子树都是二叉搜索树的情况下,左边获取最大值,右边获取最小值,进行比较。