My Solution for Validate Binary Search Tree, cpp


  • 0
    G
    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            bool flags = true, flagl = true;
            bool resl = true, resr = true;
            if (root == nullptr)
                return true;
            int sr = getSmallest(root->right, flags);
            int ll = getLargest(root->left, flagl);
            if (flags == true) {
                resr = (root->val < sr);
            }
            if (flagl == true) {
                resl = (root->val > ll);
            }
            if (resl && resr)
                return (isValidBST(root->right) && isValidBST(root->left));
            else
                return false;
        }
        
    private:
        int getSmallest(TreeNode *node, bool &flag) {
            if (node == nullptr) {
                flag = false;
                return numeric_limits<int>::max();
            }
            int res = node->val;
            while (node->left != nullptr) {
                node = node->left;
                res = node->val;
            }
            return res;
        }
        
        int getLargest(TreeNode *node, bool &flag) {
            if (node == nullptr) {
                flag = false;
                return numeric_limits<int>::min();
            }
            int res = node->val;
            while (node->right != nullptr) {
                node = node->right;
                res = node->val;
            }
            return res;
        }
    };

Log in to reply
 

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