98. Validate Binary Search Tree

Recursion

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode* root) {
        return isValid(root, nullptr, nullptr);
    }
    bool isValid(TreeNode* root, TreeNode* left, TreeNode* right) {
        if(!root) return true;

        if((left && left->val >= root->val) || right && root->val >= right->val)
            return false;

        return isValid(root->left, left, root) && isValid(root->right, root, right);
    }
};
  • T: O(N)O(N)
  • S: O(N)O(N)