98 验证二叉搜索树
中序遍历(递归直接版)
通过中序遍历得到最后的有序序列,遍历一遍有序序列看看是否递增
/**
* 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) {}
* };
*/
class Solution {
private:
vector<long long> ans;
void inOrder(TreeNode* root){
if(!root)
return;
inOrder(root->left);
ans.push_back(root->val);
inOrder(root->right);
}
public:
bool isValidBST(TreeNode* root) {
inOrder(root);
long long pre = (long long)INT_MIN - 1;
for(long long num : ans){
if(num <= pre)
return false;
pre = num;
}
return true;
}
};
但这种方法时间复杂度和空间复杂度有点高
中序遍历(递归优化版)
我们可以在中序遍历过程中判断是否符合有序序列,即只需要判断中序遍历访问的当前节点与访问的上一个节点是否满足有序
/**
* 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) {}
* };
*/
class Solution {
private:
vector<long long> ans;
long long pre = (long long)INT_MIN - 1;
bool inOrder(TreeNode* root){
if(!root)
return true;
bool leftRes = inOrder(root->left);
if(root->val <= pre)
return false;
pre = root->val;
bool rightRes = inOrder(root->right);
return leftRes && rightRes;
}
public:
bool isValidBST(TreeNode* root) {
return inOrder(root);
}
};