1. Subtree Max/Min Check (Bottom-Up)
Intuition
By definition, every node in left subtree must be < root, and every node in right subtree must be > root. Finding max in left and min in right for every node directly tests this property.
Algorithm
- Define helper findMax(root) and findMin(root).
- If root is null, return true.
- If root.left exists and findMax(root.left) >= root.val, return false.
- If root.right exists and findMin(root.right) <= root.val, return false.
- Recursively verify isValidBST(root.left) and isValidBST(root.right).
#include <iostream>#include <algorithm>#include <climits> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Solution { long long findMax(TreeNode* root) { if (!root) return LLONG_MIN; return std::max((long long)root->val, std::max(findMax(root->left), findMax(root->right))); } long long findMin(TreeNode* root) { if (!root) return LLONG_MAX; return std::min((long long)root->val, std::min(findMin(root->left), findMin(root->right))); }public: bool isValidBST(TreeNode* root) { if (!root) return true; if (root->left && findMax(root->left) >= root->val) return false; if (root->right && findMin(root->right) <= root->val) return false; return isValidBST(root->left) && isValidBST(root->right); }}; int main() { TreeNode* root = new TreeNode(2); root->left = new TreeNode(1); root->right = new TreeNode(3); Solution sol; std::cout << "IsValidBST [2,1,3]: " << (sol.isValidBST(root) ? "true" : "false") << " (Expected: true)\n"; return 0;}Time & Space Complexity
- Time complexity:
O(N^2) - Space complexity:
O(H)