Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
According to the definition of BST. left is smaller than root, right is larger than root.
I remembered that it was INT_MAX, but it seems right now, leetcode can only accept LONG_MAX....hmm....
static bool isValidBST(TreeNode* root, long long int maxRange, long long int minRange) { if(!root) return true; if(root->val >= maxRange || root->val <= minRange) return false; return isValidBST(root->left, root->val, minRange) && isValidBST(root->right, maxRange, root->val); } bool isValidBST(TreeNode* root) { if(!root) return true; return isValidBST(root, LONG_MAX, LONG_MIN); }
Maybe it is a good idea to try DFS?