递归写法,额外空间复杂度为O(1)级别,
premax原本是想写成全局变量,结果本地控制台编译通过,提交出错,尽量还是少用全局变量。
class Solution {
public:
bool isValidBST(TreeNode* root) {
long long premax=LLONG_MIN;
return bianli(root,premax);
}
bool bianli(TreeNode *root,long long &premax){
if(root==NULL)
return true;
bool isbstleft=bianli(root->left,premax);
if(isbstleft==false)
return false;
if(premax>=root->val)
return false;
else
premax=root->val;
return bianli(root->right,premax);
}
};
更新 :这道题全局变量可以使用,之前不会用,导致错误。
class Solution {
private:
long long premax=LLONG_MIN;
public:
bool isValidBST(TreeNode* root) {
//long long premax=LLONG_MIN;
return bianli(root);
}
bool bianli(TreeNode *root){
if(root==NULL)
return true;
bool isbstleft=bianli(root->left);
if(isbstleft==false)
return false;
if(premax>=root->val)
return false;
else
premax=root->val;
return bianli(root->right);
}
};
迭代中序遍历方法,利用栈完成中序遍历,弹出时压入容器。
class Solution {
public:
bool isValidBST(TreeNode* root) {
stack<TreeNode*>temp;
vector<int> ans;
TreeNode*cur=root;
// temp.push(root);
while(!temp.empty()||cur){
if(cur==NULL){
cur=temp.top()->right;
ans.push_back(temp.top()->val);
temp.pop();
}else{
temp.push(cur);
cur=cur->left;
}
}
for(int i=1;i<ans.size();i++){
if(ans[i]<=ans[i-1])
return false;
}
return true;
}
};