Day30: [LeetCode中等] 98. 验证二叉搜索树
题源:
来自leetcode题库:
https://leetcode-cn.com/problems/validate-binary-search-tree/
代码:
dirty code凑合看吧
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
/*bool f(TreeNode* root){
if(root->left==NULL&&root->right==NULL) return true;
else if(root->left==NULL) return root->val<root->right->val;
else if(root->right==NULL) return root->val>root->left->val;
return root->val<root->right->val&&root->val>root->left->val&&f(root->left)&&f(root->right);
}*/
vector<int> res;
void F(TreeNode* root){
if(root){
F(root->left);
res.push_back(root->val);
F(root->right);
}
}
bool isValidBST(TreeNode* root) {
if(!root) return true;
F(root);
for(int i=0;i<res.size()-1;i++){
if(res[i]>=res[i+1]) return false;
}
return true;
}
};