C++ 13ms easy solution (beats 88.5%)


  • 1
    A
    class Solution {
    public:
        struct DATA {
            int min;
            int max;
            bool valid;
            DATA(int min_, int max_, bool valid_): min(min_), max(max_), valid(valid_) {}
        };
        
        bool isValidBST(TreeNode* root) {
            return isValid(root).valid;
        }
        
        DATA isValid(TreeNode *root) {
            if (root==NULL) return DATA(INT_MAX,INT_MIN,true);
            DATA left = isValid(root->left);
            DATA right = isValid(root->right);
            if (!left.valid || 
                !right.valid || 
                root->left && left.max >= root->val || 
                root->right && right.min <= root->val) { 
                    return DATA(0,0,false);
                    
                }
            
            return DATA(min(min(left.min, right.min), root->val), max(max(left.max, right.max), root->val), true);
        }
    };
    

Log in to reply
 

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