Leetcode 98. Validate Binary Search Tree C++及javascript解答,不同语言不同玩法

题意:给定一棵二叉树,写程序判断这颗二叉树是否为合法的二分查找树(对于节点root,其所有左子树中节点都满足 node.val < root.val,其所有右子树中节点都满足 node.val > root.val)

转载请注明出处:http://blog.csdn.net/sunny606

C++:

/**
 * 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 isValidBSTHelper(root, numeric_limits<long long>::min(), numeric_limits<long long>::max());
    }
    
    bool isValidBSTHelper(TreeNode* root, long long int s, long long int e) {
        if(!root) {
            return true;
        }
        if(s < root->val && root->val < e) {
            if(root->left && !isValidBSTHelper(root->left, s, root->val)) {
                return false;
            }
            if(root->right && !isValidBSTHelper(root->right, root->val, e)) {
                return false;
            }
            return true;
        } else {
            return false;
        }
    }
};



javascript:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
 
var isValidBSTHelper = function(root, greater2x, less2x) {
    if(root === null) {
        return true;
    }
    if(less2x !==null && !less2x(root.val)) {
        return false;
    }
    if(greater2x !==null && !greater2x(root.val)) {
        return false;
    }
    var greater2this = function(x){
        return x > root.val;
    }
    var less2this = function(x) {
        return x < root.val;
    }
    if(root.left !==null && !isValidBSTHelper(root.left, greater2x, less2this)) {
        return false;
    }
    if(root.right !==null && !isValidBSTHelper(root.right, greater2this, less2x)) {
        return false;
    }
    return true;
}

var isValidBST = function(root) {
    return isValidBSTHelper(root, null, null);
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值