题目
分析
1.假如root节点值为a, 那么左右子树上的值用一定有个范围, 利用范围求解
2.BST有个重要的性质, 就是采用中序遍历之后的序列一定是有序的。
流程
Solution 1 : 定义两个空指针分别表示无穷大或者无穷小的值,遍历左右子树时分别将root->val 设为最大,最小值
Solution 2 : 利用BST性质, 使用中序遍历, 定义一个成员变量记录pre_value, 比较与当前值得大小,大于等于返
回False,否则返回True。
代码
Solution 1:
/**
* 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) {
return isValidBST(root, nullptr, nullptr);
}
private:
bool isValidBST(TreeNode* root, int* minval, int* maxval){
if(!root)
return true;
if((minval&& root->val <= *minval) || (maxval&& root->val >= *maxval))
return false;
return isValidBST(root->left, minval, &root->val) && isValidBST(root->right, &root->val, maxval);
}
};
Solution 2:
soulution2.1(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) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
stack<int> s;
int b = 1;
traversal(root, s, b);
if(b == 0)
return false;
else
return true;
}
void traversal(TreeNode* root, stack<int>& s, int& b){
if(!root)
return ;
traversal(root->left,s, b);
if(s.empty())
s.push(root->val);
else
if(s.top() >= root->val)
{
b = 0;
return;
}
else
{
s.push(root->val);
}
traversal(root->right, s, b);
}
};
solution2.2(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) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
return inorder(root);
}
private:
TreeNode* pre;
bool inorder(TreeNode* root){
if(!root)
return true;
if(!inorder(root->left))
return false;
if(pre && root->val <= pre->val)
return false;
pre = root;
return inorder(root->right);
}
};