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
Analysis:
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
class Solution {
public:
bool helper(TreeNode *root, int minVal, int maxVal) {
if (root == NULL)
return true;
else
return root->val < maxVal &&
root->val > minVal &&
helper(root->left, minVal, root->val) &&
helper(root->right, root->val, maxVal);
}
bool isValidBST(TreeNode *root) {
return helper(root, INT_MIN, INT_MAX);
}
};
No comments:
Post a Comment