LeetCode 98. Validate Binary Search Tree

题意

判断一棵树是否是二叉排序树

思路

递归中维护当前子树的最大值和最小值,左子树维护最大值,右子树维护最小值,然后进行判断

代码

/**
 * 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 isValid(root, NULL, NULL);
    }
    bool isValid(TreeNode* node, TreeNode* minNode, TreeNode* maxNode){
        if(node == NULL){
            return true;
        }
        if((minNode && node->val <= minNode->val) || (maxNode && node->val >= maxNode->val)){
            return false;
        }
        return isValid(node->left, minNode, node) && isValid(node->right, node, maxNode);
    }
};

你可能感兴趣的:(二叉树,LeetCode,数据结构,leetcode,二叉树,二叉排序树,BST)