98.验证二叉搜索树
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
private:
vector<int> data;
public:
// 中序遍历保证有序
void collect_num(TreeNode* root){
if(!root) return;
collect_num(root->left);
data.push_back(root->val);
collect_num(root->right);
}
bool isValidBST(TreeNode* root) {
collect_num(root);
for(int i = 1; i < data.size(); i++){
if(data[i] <= data[i - 1]){
return false;
}
}
return true;
}
};
复制代码

中序遍历二叉搜索树得到递增的有序数据,将得到的数据前后对比,若前后两个数据有不符和递增的就代表不是二叉搜索树,否则就是二叉搜索树。