Accepted BST solution


  • 0
    C
    class Solution {
    public:
    
        bool check(TreeNode *root,int mini, int maxi) {
            
            if(root==NULL) {
                return true;
            } else if (root->val < mini || root->val > maxi) {
                return false;
            } else {
                
                // To Avoid corner cases where root->val == INT_MAX or INT_MIN and child also have similar values
                if (root->left!=NULL && root->left->val == root->val) {
                    return false;
                } else if (root->right!=NULL && root->right->val == root->val) {
                    return false;
                }
                
                
                if (root->val == INT_MIN){
                    return check(root->left, mini, root->val) && check(root->right, root->val+1, maxi);
                } else if (root->val == INT_MAX){
                    return check(root->left, mini, root->val-1) && check(root->right, root->val, maxi);
                } else {
                    return check(root->left, mini, root->val-1) && check(root->right, root->val+1, maxi);
                }
            }
        }
    
        bool isValidBST(TreeNode *root) {
            return check(root, INT_MIN, INT_MAX);
        }
    };

Log in to reply
 

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