题解 | #判断是不是二叉搜索树#
判断是不是二叉搜索树
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布尔型
*/
int min = INT_MIN;
//判断BST我们使用他的性质,BST的中序遍历是有序的。
//那么我们可以在遍历的过程中判断:遍历序列中的前一个结点的值小于当前结点。继续,否者可以直接返回false
bool isBST(TreeNode* tree)
{
if(tree == nullptr) return true;
//处理左子树
if(!isBST(tree->left)) return false;
//处理当前结点
if(tree->val <= min) return false;
else min = tree->val;
//处理右子树
if(!isBST(tree->right)) return false;
return true;
}
bool isValidBST(TreeNode* root) {
// write code here
if(root == nullptr) return true;
return isBST(root);
}
};
查看22道真题和解析
