98. Validate Binary Search Tree

image.png

解法一,将中序遍历的结果保存下来,如果是BST的话,数组应为递增的

/**
 * 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) {
        if(root == NULL) return true;
        vector nums;
        inorder(root, nums);
        for(int i = 1; i < nums.size(); i++){
            if(nums[i] <= nums[i-1]) return false;
        }
        return true;
        
    }
private:
    void inorder(TreeNode* root, vector &nums){
        if(root == NULL) return;
        inorder(root->left, nums);
        nums.push_back(root->val);
        inorder(root->right, nums);
    }
};

!!!解法二:
注意类型 long LONG_MIN LONG_MAX
并且不可以与节点值相同,所以判断要等号

/**
 * 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) {
        if(root == NULL) return true;
        return helper(root, LONG_MIN, LONG_MAX);
    }
private:
    bool helper(TreeNode* node, long min, long max){
        if(node == NULL) return true;
        if(node->val <= min || node->val >= max) return false;
        bool isleft = helper(node->left, min, node->val);
        bool isright = helper(node->right, node->val , max );
        return isleft && isright;
    }
};

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