> Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.
Copy bool _isBST(TreeNode * node, int min_, int max_)
{
if(node == NULL) return true;
if(node->val <= min_ || node->val >= max_) return false;
return _isBST(node->left, min_, node->val)
&& _isBST(node->right, node->val, max_);
}
bool isValidBST(TreeNode *root)
{
return _isBST(root, INT_MIN, INT_MAX);
}
Copy bool isValidBST(TreeNode *root)
{
stack<TreeNode*> stacks;
TreeNode * node = root;
int last = INT_MIN;
while(true)
{
if(node)
{
stacks.push(node);
node = node->left;
}else
{
if(stacks.empty()) break;
node = stacks.top(); stacks.pop();
if(last >= node->val) return false;
last = node->val;
node = node->right;
}
}
return true;
}
Copy bool isValidBST(TreeNode *root)
{
TreeNode * node = root;
int last = INT_MIN;
bool result = true;
while(node)
{
if(node->left == NULL)
{
if(last >= node->val) result = false;;
last = node->val;
node = node->right;
}else
{
auto pre = node->left;
while(pre->right != NULL && pre->right != node)
pre = pre->right;
if(pre->right == NULL)
{
pre->right = node;
node= node->left;
}else
{
if(last >= node->val) result = false;//cannot return. return false;
pre->right = NULL;//reset
last = node->val;
node = node->right;
}
}
}
return result;
}