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.
confused what
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
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.
confused what
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ. /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#define INT_MIN 0x8FFFFFFF
#define INT_MAX 0x7FFFFFFF
bool isValidBSTRecurse(TreeNode *root,int maxVal, int minVal)
{
if(!root)
{
return true;
}
if(root->val >= maxVal || root->val <= minVal)return false;
int x = isValidBSTRecurse(root->left,root->val, minVal);
int y = isValidBSTRecurse(root->right,maxVal, root->val);
return (x&&y);
}
bool isValidBST(TreeNode *root) {
int maxVal = 0x7FFFFFFF, minVal = 0x8FFFFFFF;
return isValidBSTRecurse(root,maxVal, minVal);
}
No comments:
Post a Comment