Validate Binary Search Tree

时间:2022-06-22
本文章向大家介绍Validate Binary Search Tree,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. Description

2. Solution

  • Recurrent
/**
 * 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);
    }
};