美文网首页
98. Validate Binary Search Tree

98. Validate Binary Search Tree

作者: 刘小小gogo | 来源:发表于2018-08-19 22:27 被阅读0次
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<int> 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<int> &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

      本文链接:https://www.haomeiwen.com/subject/sushiftx.html