[LeetCode] Validate Binary Search Tree

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.

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

class Solution {
public:
    bool isValidBST(TreeNode *root) {
         return check(root, -(1<<30), 1<<30);
    }
    
    bool check(TreeNode* cur, int min_num ,int max_num) {
        if (cur == NULL) return true;
        if (cur->val > min_num && cur->val < max_num 
            && check(cur->left, min_num, cur->val)
            && check(cur->right, cur->val, max_num))
            return true;
        else return false;
    }
};

猜你喜欢

转载自cozilla.iteye.com/blog/1856835