题解 | #判断是不是二叉搜索树#
判断是不是二叉搜索树
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) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return bool布尔型
*/
int find_min(TreeNode* root) {
while (root->left != nullptr) root = root->left;
return root->val;
}
int find_max(TreeNode* root) {
while (root->right != nullptr) root = root->right;
return root->val;
}
bool isValidBST(TreeNode* root) {
int leftval, rightval;
if (root == nullptr) return true;
if (isValidBST(root->left) && isValidBST(root->right)) {
if (root->left != nullptr && root->right != nullptr) {
leftval = find_max(root->left);
rightval = find_min(root->right);
if (leftval < root->val && root->val < rightval) return true;
else return false;
}
if (root->left == nullptr && root->right != nullptr) {
rightval = find_min(root->right);
if (root->val < rightval) return true;
else return false;
}
if (root->left != nullptr && root->right == nullptr) {
leftval = find_max(root->left);
if (leftval < root->val) return true;
else return false;
}
if (root->left == nullptr && root->right == nullptr) {
return true;
}
}else{
return false;
}
return true;
}
};
比较当前结点的值是否在左子树的最大值右子树的最小值之间
二叉搜索树BST
某一个二叉树,对于所有结点满足
左子树的所有制均小于节点值,右子树的所有值均大于节点值
爱玛科技公司福利 8人发布
