leetcode Day7 二叉树

112 阅读1分钟

1、先写一个今天上午面试考到的用var和定时器实顺序输出012345678910

for(var i=0;i<=10;i++){
    setTimeout(()=>console.log(i))
}
//这样会输出1111,因为setTimeout是宏任务,var不存在块级作用域
//当主代码执行结束,执行微任务时,i是同一个i,全局作用域里面的i,此时i会保存导致循环退出时的i,即11

可以用闭包保存每次循环时的i值,用立即执行函数模拟块级作用域

for(var i=0;i<=10;i++){
    (function(i){
        setTimeout(function(){
            console.log(i)
        },0)
    }(i))
}
//每次把i传进去,i保留的是当时的i,相当于循环结束后,有11个块级作用域

819. 最常见的单词

var mostCommonWord = function(paragraph, banned) {
    paragraph = paragraph.toLowerCase().replace(/[!?',;.]/g, ' ');
    let strArr=paragraph.split(' ')
    let strMap=new Map()
    for(let i of strArr){
        if(i!==''){
            strMap.set(i,strMap.has(i)?strMap.get(i)+1:1)
        }
    }
    let newArr=Array.from(strMap)
    newArr.sort((a,b)=>b[1]-a[1])
    for(let [key,values] of newArr){
        if(banned.indexOf(key)!==-1)continue
        else{
            return key
        }
    }
};

110. 平衡二叉树

var isBalanced = function(root) {
    if(root===null)return true
    let leftDepth=getDepth(root.left)
    let rightDepth=getDepth(root.right)
    if(Math.abs(leftDepth-rightDepth)>1){
        return false
    }
    return isBalanced(root.left) && isBalanced(root.right)

};
//获取树的高度
const getDepth=function(node){
    if(node===null){
        return 0
    }
    return Math.max(getDepth(node.left),getDepth(node.right))+1
}

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

太厉害啦!自己写出来啦!

var lowestCommonAncestor = function(root, p, q) {
    let pPath=getPath(root,p)
    let qPath=getPath(root,q)
    for(let i=pPath.length-1;i>=0;i--){
        if(qPath.indexOf(pPath[i])!==-1){
            return pPath[i]
        }
    }
};
const getPath=function(root,node){
    let cur=root
    let path=[]
    while(cur!==null){
        path.push(cur)
        if(cur===node){
            return path
        }
        else if(cur.val>node.val){
            cur=cur.left
        }
        else{
            cur=cur.right
        }
    }
    return path
}

257. 二叉树的所有路径

var binaryTreePaths = function(root) {
    if(root===null)return []
    let res=[]
    const getPath=function(node,path){
        if(node){
            path=path+node.val.toString()
            if(!node.left && !node.right){
                res.push(path)
            }
            else{
                path=path+'->'
                getPath(node.left,path)
                getPath(node.right,path)
            }
        }
    }
    getPath(root,'')
    return res
};