1.中序遍历递归
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return bool布尔型
*/
void inorder(TreeNode* root,vector<int> &res)
{
if(!root)
return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
bool isValidBST(TreeNode* root) {
if(!root)
return true;
if(!isValidBST(root->left))
return false;
if(root->val <= pre)
return false;
pre = root->val;
if(!isValidBST(root->right))
return false;
return true;
}
};
2.获取中序遍历的结果然后检查是否严格递增
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return bool布尔型
*/
void inorder(TreeNode* root,vector<int> &res)
{
if(!root)
return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
long pre = INT_MIN;
bool isValidBST(TreeNode* root) {
// write code here
vector<int> res;
inorder(root, res);
if(res.size() <= 1)
return true;
for(int i = 1;i<res.size();++i)
{
if(res[i] <= res[i-1])
return false;
}
return true;
}
};
class Solution {
public:
bool isValidBST(TreeNode* root) {
//使用栈获取中序遍历的结果
stack<TreeNode*> s;
TreeNode* head = root;
vector<int> res; //记录中序遍历的数组
while(head != NULL || !s.empty()){
//直到没有左节点
while(head != NULL){
s.push(head);
head = head->left;
}
head = s.top();
s.pop();
//访问节点
res.push_back(head->val);
head = head->right;
}
if(res.size() <= 1)
return true;
for(int i = 1;i<res.size();++i)
{
if(res[i] <= res[i-1])
return false;
}
return true;
}
};



京公网安备 11010502036488号