Skip to content

Latest commit

 

History

History
60 lines (43 loc) · 1.41 KB

_98. Validate Binary Search Tree.md

File metadata and controls

60 lines (43 loc) · 1.41 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 23, 2024

Last updated : June 23, 2024


Related Topics : Tree, Depth-First Search, Binary Search Tree, Binary Tree

Acceptance Rate : 33.78 %


Solutions

C

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

bool isValidBSTHelper(struct TreeNode* root, long min, long max) {
    if (!root) 
        return true;

    if ((long) root->val <= min || (long) root->val >= max) 
        return false;

    bool output = true;
    
    if (root->right)
        output &= root->val < root->right->val
                    && isValidBSTHelper(root->right, (long) root->val, max);

    if (root->left)
        output &= root->left->val < root->val
                    && isValidBSTHelper(root->left, min, (long) root->val);

    return output;
}

bool isValidBST(struct TreeNode* root) {
    return isValidBSTHelper(root, LONG_MIN, LONG_MAX);
}