Simple and 10 lines c++ recurive solution

  • 4
    class Solution {
            bool isValidBST(TreeNode *root) {
                long long min = LLONG_MIN, max = LLONG_MAX;
                return isValidBST(root, min, max);
            bool isValidBST(TreeNode *node, long long min, long long max){
                if(node == NULL)
                    return true;
                if(node->val <= min || node->val >= max)
                    return false;
                if(!isValidBST(node->left, min, node->val) || !isValidBST(node->right, node->val, max))
                    return false;
                return true;

  • 0

    Thanks for sharing.

    The last return true can be left out actually, as the last if will do the judgement call.

    Here is my code FYI

    var isValidBST = function(root) {
        function checkBST(root, min, max) {
            if (!root) return true;
            if (root.val >= max || root.val <= min) return false; //according to definition, no equal is allowed.
            return checkBST(root.left, min, root.val) && checkBST(root.right, root.val, max);
        return checkBST(root, -Number.MAX_VALUE, Number.MAX_VALUE);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.