98. Verify Binary Search Tree

Given a binary tree, determine whether it is a valid binary search tree.

Suppose a binary search tree has the following characteristics:

The left subtree of a node contains only numbers less than the current node.
The right subtree of a node contains only numbers greater than the current node.
All left and right subtrees must themselves be binary search trees.
Example 1:

Input:
2
/
1 3
Output: true
Example 2:

Input:
5
/
1 4
/
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6].
The root node has a value of 5, but its right child has a value of 4.

在这里插入代码片

class Solution {
    
    
public:
    bool isValidBST(TreeNode* root) {
    
    
        return isValidBST(root, nullptr, nullptr);
    }
    bool isValidBST(TreeNode* root, TreeNode* min, TreeNode* max) {
    
    
        if(root == nullptr) return true;
        if(min != nullptr && root->val <= min->val) return false;
        if(max != nullptr && root->val >= max->val) return false;
        return isValidBST(root->left, min, root) && isValidBST(root->right, root, max);
    }

};

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324072705&siteId=291194637