leecode Day45 剑指专项 43-45

62 阅读1分钟

1037. 有效的回旋镖

var isBoomerang = function(points) {
    let x1 = points[0][0] - points[1][0];
    let y1 = points[0][1] - points[1][1]; 
    let x2 = points[0][0] - points[2][0];
    let y2 = points[0][1] - points[2][1]; 
    return x1 * y2 != x2 * y1;
};

剑指 Offer II 043. 往完全二叉树添加节点

var CBTInserter = function(root) {
    this.root=root
    this.queue=[]
};

/** 
 * @param {number} v
 * @return {number}
 */
CBTInserter.prototype.insert = function(v) {
    let node=new TreeNode(v)
    this.queue.push(this.root)
    while(this.queue[0].left && this.queue[0].right){
        this.queue.push(this.queue[0].left)
        this.queue.push(this.queue[0].right)
        this.queue.shift()
    }
    this.queue[0].left==null?(this.queue[0].left = node):(this.queue[0].right=node);
    return this.queue[0].val;
};

/**
 * @return {TreeNode}
 */
CBTInserter.prototype.get_root = function() {
    return this.root
};

剑指 Offer II 044. 二叉树每层的最大值

var largestValues = function(root) {
    if(!root){
        return []
    }
    let res=[]
    let queue=[root]
    while(queue.length){
        let l=queue.length
        let cur=[]
        for(let i=0;i<l;i++){
            let node=queue.shift()
            cur.push(node.val)
            if(node.left){
                queue.push(node.left)
            }
            if(node.right){
                queue.push(node.right)
            }
        }
        res.push(Math.max(...cur))
    }
    return res
};

剑指 Offer II 045. 二叉树最底层最左边的值

var findBottomLeftValue = function(root) {
    let res=[]
    let queue=[root]
    while(queue.length){
        let l=queue.length
        for(let i=0;i<l;i++){
            let node=queue.shift()
            res.push(node.val)
            if(node.right){
                queue.push(node.right)
            }
            if(node.left){
                queue.push(node.left)
            }
        }
    }
    return res[res.length-1]
};