题解 | #递归——判断是不是二叉搜索树#
判断是不是二叉搜索树
https://www.nowcoder.com/practice/a69242b39baf45dea217815c7dedb52b
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <climits>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return bool布尔型
*/
bool Bst(TreeNode *root,int min,int max){
if(root == NULL) return true;
if(root->val<min || root->val > max) return false;
//递归左右子树。min是上一层传递进来的min,max是上一层传递进来的max,保证了左子树全部小于根结点,右子树全部大于根结点
return Bst(root->left,min,root->val) && Bst(root->right, root->val,max);
}
bool isValidBST(TreeNode* root) {
// write code here
return Bst(root,INT_MIN,INT_MAX);
}
};


查看17道真题和解析