我觉得我的思路算是比较烂。这道题应该有挺多更优的算法。
我是通过前序遍历,将树中的所有节点的值放进一个vector数组之中,然后再遍历这个数组,如果数组不是严格升序,那么返回false。时间空间消耗感觉都挺大的,因为遍历了两次。
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root == NULL)
return NULL;
if(root->val == val){
return root;
}
else if(root->val > val){
return searchBST(root->left, val);
}
else{
return searchBST(root->right, val);
}
}
};
写的时候想到了一个只需要遍历一遍的加标签的方法。
class Solution {
public:
bool isValidBST(TreeNode* root){
vector<int> temp;
bool flag = true;
Tr(root,temp,flag);
return flag;
}
void Tr(TreeNode* root,vector<int>& temp,bool& flag){
if(root == NULL) return;
Tr(root->left,temp,flag);
if(temp.size() != 0 && !(temp[temp.size() - 1] < root->val)){
flag = false;
return;
}
temp.push_back(root->val);
Tr(root->right,temp,flag);
}
};
结果并没有降低时间和空间的消耗。
然后把vector数组改成了一个常数。。就降低了很多。因为不用每次都取数组的size查询了吧、内存消耗上打败的比例也远高于其他人,不过看起来内存消耗也没少多少。。
class Solution {
public:
bool isValidBST(TreeNode* root){
long long int minnum = getmin(root) - 1;
bool flag = true;
Tr(root,minnum,flag);
return flag;
}
long long int getmin(TreeNode* root){
while(root->left != NULL)
root = root->left;
return (root->val);
}
void Tr(TreeNode* root,long long int& temp,bool& flag){
if(root == NULL) return;
Tr(root->left,temp,flag);
if(!(temp < root->val)){
flag = false;
return;
}
temp = root->val;
Tr(root->right,temp,flag);
}
};
贴个图表示喜悦: