题解 | #判断是不是二叉搜索树#
判断是不是二叉搜索树
https://www.nowcoder.com/practice/a69242b39baf45dea217815c7dedb52b
bool isValidBST(struct TreeNode* root ) {
// write code here
if (root == NULL)
return true;
struct TreeNode* leftmax = root->left, *rightmin = root->right;
if (leftmax != NULL) {
while (leftmax->right != NULL)
leftmax = leftmax->right;
if (leftmax->val > root->val )
return false;
}
if (rightmin != NULL) {
while (rightmin->left != NULL)
rightmin = rightmin->left;
if (rightmin->val < root->val)
return false;
}
if (root->left == NULL || (root->left->val < root->val &&
isValidBST(root->left )) )
if (root->right == NULL || (root->right->val > root->val &&
isValidBST(root->right )) )
return true;
return false;
}
查看30道真题和解析