美文网首页
98. Validate Binary Search Tree两

98. Validate Binary Search Tree两

作者: 羲牧 | 来源:发表于2016-10-02 17:33 被阅读56次

判断是否为二叉查找树的题,先给一种方法,可是过不去某个case

/**
 * 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:
//这种方法当test case为[-2147483648,null,2147483647]或[-2147483648]或[2147483647]时无法通过
    bool isValidBST(TreeNode* root) 
        return helper(root, INT_MIN, INT_MAX);
        
    }
    bool helper(TreeNode* root, int min, int max){
        if(root == NULL) return true;
        
        if(root->val <= min || root->val >= max)
            return false;
        return helper(root->left, min, root->val) && helper(root->right, root->val, max);
        
    }
};

换另外一种方法(In-order tranversal):

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

这题值得好好回味一下

相关文章

网友评论

      本文标题:98. Validate Binary Search Tree两

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