题目描述
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
C++
我写的,,有些麻烦
/**
* 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) {}
* };
*/
/*
用栈存中序遍历形成的升序,
然后遍历栈,发现不是升序就返回false
*/
class Solution {
stack<int> thisstack;
public:
bool isValidBST(TreeNode* root) {
if(!root) return true;
middle(root);
int pre=thisstack.top();
thisstack.pop();
while(!thisstack.empty()){
if(thisstack.top()>=pre)
return false;
pre=thisstack.top();
thisstack.pop();
}
return true;
}
void middle(TreeNode* root){
if(!root) return;
middle(root->left);
thisstack.push(root->val);
middle(root->right);
}
};
别人写的
/**
* 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) {}
* };
*/
/*
中序遍历形成升序,如果不成为升序就返回false
*/
class Solution {
double pre=-DBL_MAX; //用int pre=INR_MIN错误
public:
bool isValidBST(TreeNode* root) {
if(!root) return true;
if(isValidBST(root->left)){
if(root->val>pre)
{
pre=(double)root->val;
return isValidBST(root->right);
}
}
return false;
}
};
再简洁一些
/**
* 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) {}
* };
*/
/*
中序遍历形成升序,如果不成为升序就返回false
*/
class Solution {
double pre=-DBL_MAX;
public:
bool isValidBST(TreeNode* root) {
if(!root) return true;
return isValidBST(root->left) && pre<(pre=root->val) && isValidBST(root->right);
}
};