题目链接:https://leetcode-cn.com/problems/validate-binary-search-tree/
题目如下:
注:一二为递归,三四为非递归
解法一:(大宝的)
/**
* 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 {
public:
long long pre=LONG_MIN;
bool flag=true;
void dfs(TreeNode* root) {
if (!root) return;
if (!flag) return;
dfs(root->left);
if (root->val <= pre) flag=false;
pre=root->val;
dfs(root->right);
}
bool isValidBST(TreeNode* root) {
//conclusion:二叉搜索树的中序遍历都是有序的
dfs(root);
return flag;
}
};
解法二:(大宝的)
/**
* 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 {
public:
long long pre=LONG_MIN;
bool dfs(TreeNode*root) {
if (!root) return true;
//如果左子树为空,则不执行该语句
if (!dfs(root->left)) { //如果返回true,则为false,不执行语句
return false;
}
if (root->val <= pre) return false;//二叉搜索树中,pre即左孩子应<root->val
else pre=root->val;
return dfs(root->right);
}
bool isValidBST(TreeNode* root) {
//conclusion:二叉搜索树的中序遍历都是有序的
return dfs(root);
}
};
解法三:(我的)
/**
* 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 {
public:
bool isValidBST(TreeNode* root) {
//结论:二叉搜索树的中序遍历都是有序的
vector<int> inorder;
stack<TreeNode*> stk;
while(root||stk.size()){
while(root){
stk.push(root);
root=root->left;
}
root=stk.top();
stk.pop();
inorder.push_back(root->val);
root=root->right;
}
for(int i=0;i<inorder.size()-1;i++){
if(inorder[i]>=inorder[i+1]) return false;
}
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 {
public:
bool isValidBST(TreeNode* root) {
//conclusion:二叉搜索树的中序遍历都是有序的
vector<int> inorder;
stack<TreeNode*> stk;
long pre=LONG_MIN;
while(root||stk.size()){
while(root){
stk.push(root);
root=root->left;
}
auto t=stk.top();
stk.pop();
if (t->val <= pre) return false;
pre=t->val;
root=t;
root=root->right;
}
return true;
}
};