【leetcode】Validate Binary Search Tree 题解三种思路

https://leetcode.com/submissions/detail/39976412/



//2015-10-22 20:58:42 
//1.中序 保存在一个vector中,检查是否有序
//2.传递前驱指针,看是否有序
//3.从底向上 ,开始只传递回最大值,不对,比如右侧应该传回最小值,因此改为两个返回值
//2015-10-22 21:24:21
/**
 * 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;
        }
        int leftmin,rightmax = 0;
        return check(root,leftmin,rightmax);
    }
    
    bool check(TreeNode *root,int &leftmin,int &rightmax){
        if(root == NULL){
            return true;
        }
        leftmin = root->val;
        rightmax = root->val;
        if(root->left==NULL &&root->right==NULL){
            return true;
        }
        
        int left,right;
        
        if(root->left != NULL){
            if(check(root->left,left,right) == false || right>=root->val){
                return false;
            }
            leftmin = left;
        }
        if(root->right != NULL){
            if(check(root->right,left,right)==false || left<=root->val){
                return false;
            }
            rightmax = right;
        }
        
        return true;
    }
    
};

另外,还有一种是从顶向下的递归方法,每次把两个边界传递过来,初始值有问题,例如设为INT_MIN 或INT_MAX,如果测试用例中包含该值则出错。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值