题解 | #判断是不是二叉搜索树#
判断是不是二叉搜索树
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布尔型
*/
// 中序遍历
void inorder(TreeNode* root, vector<int>& res) {
if (!root)
return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
// 判断是否是二叉搜索树
bool isValidBST(TreeNode* root) {
vector<int> res;
inorder(root, res);
// 只要检测到递减序,就返回false
for (int i = 0; i < res.size() - 1; i++) {
if (res[i] > res[i + 1])
return false;
}
return true;
}
};
查看29道真题和解析
腾讯云智研发成长空间 240人发布
