方法一:递归
错误:只是局部满足要求,整体不满足。
bool isValidBST(struct TreeNode* root){
if( root == NULL ) return true;
if( root->left != NULL && root->left->val > root->val )
return false;
if( root->right != NULL && root->right->val < root->val )
return false;
if( !isValidBST(root->left) || !isValidBST(root->right) )
return false;
return true;
}
有参数记录整体最大最小值
class Solution {
public:
bool helper(TreeNode* root, long long lower, long long upper) {
if (root == nullptr)
return true;
if (root -> val <= lower || root -> val >= upper) return false;
return helper(root -> left, lower, root -> val) && helper(root -> right, root -> val, upper);
}
bool isValidBST(TreeNode* root) {
return helper(root, LONG_MIN, LONG_MAX);
}
};
方法一:中序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
stack<TreeNode*> st;
long min=LONG_MIN;
while(root|| !st.empty()){
while(root){ //遍历到最左下端
st.push(root);
root=root->left;
}
root=st.top();
st.pop();
if(root->val<=min)
return false;
min=root->val;
root=root->right;
}
return true;
}
};