C++ solution


  • 0
    Z
    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            long min, max;
            return valid(root, min, max);
        }
        
        bool valid(TreeNode *root, long& min, long& max) {
            if(!root) {
                min = LONG_MAX;
                max = LONG_MIN;
                return true;
            }
            long lmin, lmax, rmin, rmax;
            bool ret = valid(root -> left, lmin, lmax) && valid(root -> right, rmin, rmax) &&
                    root -> val > lmax && root -> val < rmin;
            min = std::min((long)root -> val, std::min(lmin, rmin));
            max = std::max((long)root -> val, std::max(lmax, rmax));
            return ret;
            
        }
        
    };
    

Log in to reply
 

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