1、递归
pair<int, int> minandmax(TreeNode* root) {
int minn, maxx;
if (root->left == NULL)
minn = root->val;
else
minn = min(root->val, minandmax(root->left).first);
if (root->right == NULL)
maxx = root->val;
else
maxx = max(root->val, minandmax(root->right).second);
return make_pair(minn, maxx);
}
bool isValidBST(TreeNode* root) {
if (root == NULL)
return true;
if (root->left != NULL && root->val <= minandmax(root->left).second) {
return false;
}
if (root->right != NULL && root->val >= minandmax(root->right).first)
return false;
if (isValidBST(root->left) && isValidBST(root->right))
return true;
return false;
}
2、中序遍历
bool isValidBST(TreeNode* root) {
if (root == NULL) {
return false;
}
stack<TreeNode*> st;
TreeNode* cur = root;
long long pre = (long long)INT_MIN - 1;
st.push(cur);
while (!st.empty()) {
while (cur != NULL) {
cur = cur->left;
if (cur != NULL) {
st.push(cur);
}
}
cur = st.top();
st.pop();
if (cur->val <= pre) {
return false;
}
else {
pre = cur->val;
}
cur = cur->right;
if (cur != NULL) {
st.push(cur);
}
}
return true;
}