LeetCode //C - 98. Validate Binary Search Tree

98. Validate Binary Search Tree

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.
     
Example 1:

LeetCode //C - 98. Validate Binary Search Tree_第1张图片

Input: root = [2,1,3]
Output: true

Example 2:

LeetCode //C - 98. Validate Binary Search Tree_第2张图片

Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node’s value is 5 but its right child’s value is 4.

Constraints:
  • The number of nodes in the tree is in the range [ 1 , 1 0 4 1, 10^4 1,104].
  • − 2 31 < = N o d e . v a l < = 2 31 − 1 -2^{31} <= Node.val <= 2^{31} - 1 231<=Node.val<=2311

From: LeetCode
Link: 98. Validate Binary Search Tree


Solution:

Ideas:

1. Initialization: The function isValidBST initializes the validation process by calling the helper function with the entire valid integer range.

2. Base Case: If the current node is nullptr, it means we’ve reached a leaf node, and we return true since a leaf node is trivially a BST.

3. Value Check: For any other node, we check if its value lies within the permissible range (lower and upper).

  • If the value lies outside this range, the BST property is violated, and we return false.

4. Recursive Calls:

  • For the left child, we update the upper boundary to the current node’s value because all values in the left subtree should be less than the current node’s value.
  • For the right child, we update the lower boundary to the current node’s value because all values in the right subtree should be greater than the current node’s value.

5. Combining Results: The final result for the current node is a logical AND (&&) of the results from the left and right subtrees. This ensures that both subtrees must be valid BSTs for the current tree to be a BST.

Code:
/**
 * 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 helper(root, LONG_MIN, LONG_MAX);
    }
    
    bool helper(TreeNode* node, long long lower, long long upper) {
        if (!node) return true;
        
        if (node->val <= lower || node->val >= upper) {
            return false;
        }
        
        return helper(node->left, lower, node->val) && 
               helper(node->right, node->val, upper);
    }
};

你可能感兴趣的:(LeetCode,leetcode,c语言,算法)