Untitled
unknown
c_cpp
10 months ago
1.9 kB
8
Indexable
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> help(TreeNode* root ){
vector<int> res;
if(root == nullptr) return res;
if(root->right){
res.push_back(root->right->val);
vector<int> rightT = help(root->right);
res.insert(res.end(), rightT.begin(), rightT.end());
}
if(root->left){
res.push_back(root->left->val);
vector<int> leftT = help(root->left);
res.insert(res.end(),leftT.begin(),leftT.end());
}
return res;
}
bool isValidBST(TreeNode* root) {
if(root == nullptr){
return true;
}
if(root->right){
vector <int> h = help(root->right);
bool x = true;
for(auto&element : h){
if(element <= root->val) {x = false;break;}
}
if(!x || root->val >= root->right->val || !isValidBST(root->right)) return false;
}
if(root->left){
vector<int> subL = help(root->left);
bool x = true;
for(auto& element: subL){
if(element >= root->val){
x = false;
break;
}
}
if(!x || root->val <= root->left->val || !isValidBST(root->left)) return false;
// return x && root->val > root->left->val && isValidBST(root->left);
}
return true;
}
};
Editor is loading...
Leave a Comment