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

Assume a 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.
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution{
public:
    TreeNode* pre = nullptr;
    bool isValidBST(TreeNode* root){
        if(root == nullptr) return true;
        if(!isValidBST(root->left)) return false;
        if(pre && root->val <= pre->val){
            return false;
        }
        pre = root;
        if(!isValidBST(root->right)) return false;
        return true;
    }

};

 

相关文章:

  • 2022-12-23
  • 2021-12-28
  • 2021-08-04
  • 2022-12-23
  • 2021-10-19
  • 2021-11-18
  • 2021-09-20
  • 2021-07-04
猜你喜欢
  • 2021-05-16
  • 2021-04-14
  • 2022-01-01
  • 2021-10-13
  • 2021-09-01
相关资源
相似解决方案