LeetCode 98. Validate Binary Search Tree

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.

According to the definition of BST. left is smaller than root, right is larger than root.

I remembered that it was INT_MAX, but it seems right now, leetcode can only accept LONG_MAX....hmm....

    static bool isValidBST(TreeNode* root, long long int maxRange, long long int minRange) {
        if(!root) return true;
        if(root->val >= maxRange || root->val <= minRange) return false;
        return isValidBST(root->left, root->val, minRange) && isValidBST(root->right, maxRange, root->val);
    }
    bool isValidBST(TreeNode* root) {
        if(!root) return true;
        return isValidBST(root, LONG_MAX, LONG_MIN);
    }

Maybe it is a good idea to try DFS?

你可能感兴趣的:(LeetCode 98. Validate Binary Search Tree)