Validate Binary Search Tree

2019-05-25 22:49:15 浏览数 (1)

1. Description

2. Solution

  • Recurrent
代码语言:javascript复制
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode* root) {
        return validate(root, nullptr, nullptr);
    }

private:
    bool validate(TreeNode* root, TreeNode* max, TreeNode* min) {
        if(!root) {
            return true;
        }
        if((min && root->val <= min->val) || (max && root->val >= max->val)) {
            return false;
        }
        return validate(root->left, root, min) && validate(root->right, max, root);
    }
};

0 人点赞