1.8 LeetCode(剑指Offer)

116 阅读1分钟

64.求1+2+3+...+n

// 这个题目居然考语言特性...不过确实可以用&&代替一些判断。
// 如果满足前置条件就继续执行,否则就不会执行下一步。
var sumNums = function(n) {
    let res = 0;
    res = n&&n+sumNums(n-1);
    return res;
};

68.I二叉搜索树的最近公共祖先

//救命,我居然忘了在后面加上return了,直接给我显示null
var lowestCommonAncestor = function (root, p, q) {
    var helper = (root) => {
        let x = Math.max(p.val, q.val);
        let y = Math.min(p.val, q.val);
        if (!root || (x >= root.val && y <= root.val)) {
            return root;
        }
        if (x < root.val) {
            return helper(root.left);
        }
        else {
            return helper(root.right);
        }
    }
    return helper(root);
};