My c++ solution 12ms,easy to understand


  • 5
    W
    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            if(root==NULL)
            return true;
            if(root->left==NULL && root->right==NULL)
            return true;
            bool left=true;
            bool right=true;
            if(root->left)
            {
                left=isValidBST(root->left);
                TreeNode* rightest=root->left;
                while(rightest->right)
                {
                    rightest=rightest->right;
                }
                left=left&&(root->val>rightest->val);
            }
            if(root->right)
            {
                right=isValidBST(root->right);
                TreeNode* leftest=root->right;
                while(leftest->left)
                leftest=leftest->left;
                right=right&&(root->val<leftest->val);
            }
            return left&&right;
        }
    };

Log in to reply
 

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