If Max of left Subtree < root && Min of right Subtree > root
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class ResultType {
public:
TreeNode* minNode;
TreeNode* maxNode;
bool isValid;
ResultType() {
minNode = NULL;
maxNode = NULL;
isValid = true;
}
};
class Solution {
public:
/*
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
bool isValidBST(TreeNode * root) {
// write your code here
return check(root).isValid;
}
ResultType check (TreeNode* root) {
ResultType result;
if (root == NULL) {
return result;
}
ResultType leftNode = check(root->left);
ResultType rightNode = check(root->right);
if (!leftNode.isValid || !rightNode.isValid) {
result.isValid = false;
return result;
}
if (leftNode.maxNode != NULL && leftNode.maxNode->val >= root->val ) {
result.isValid = false;
return result;
}
if (rightNode.minNode != NULL && rightNode.minNode->val <= root->val) {
result.isValid = false;
return result;
}
if (leftNode.minNode != NULL) {
result.minNode = leftNode.minNode;
} else {
result.minNode = root;
}
if (rightNode.maxNode != NULL) {
result.maxNode = rightNode.maxNode;
} else {
result.maxNode = root;
}
return result;
}
};