leetcode 二叉树最大宽度 && 二叉树中的最长交错路径 && 路径总和 II

136 阅读1分钟

662. 二叉树最大宽度

leetcode-cn.com/problems/ma…

  • bfs 注意大数 因此用bigint
var widthOfBinaryTree = function (root) {
    const stack = [{
        node: root,
        pos: 1n
    }]
    let maxCounter = 0n
    while (stack.length) {

        const size = stack.length
        let posLeft = stack[0].pos
        let posRight = stack[stack.length -1].pos
        if(maxCounter - (posRight - posLeft + 1n) < 0n){
            maxCounter = posRight - posLeft + 1n
        }
        for (let i = 0; i < size; i++) {
            const { node, pos } = stack.shift()
            if (node.left) {
                stack.push({
                    node: node.left,
                    pos: 2n * pos  
                })
            }
            if(node.right){
                stack.push({
                    node: node.right,
                    pos: 2n * pos + 1n
                })
            }
        }
    }
    return maxCounter
};

1372. 二叉树中的最长交错路径

leetcode-cn.com/problems/lo…

  • dfs
var longestZigZag = function (root) {
    const Left = -1
    const Right = 1
    let maxCounter = 0
    const dfs = (node, dir, counter) => {
        if (node === null) {
            return
        }
        
        maxCounter = Math.max(maxCounter, counter)

        if (dir === Left) {
            dfs(node.left, Left, 1)
            dfs(node.right, Right, counter + 1)
        }
        if (dir === Right) {
            dfs(node.left, Left, counter + 1)
            dfs(node.right, Right, 1)
        }
        
    }
    dfs(root.left, Left, 1)
    dfs(root.right, Right, 1)
    return maxCounter
};

113. 路径总和 II

leetcode-cn.com/problems/pa…

  • dfs
var pathSum = function(root, targetSum) {
    const paths = []

    // 返回pathSum
    const dfs = (node,path,pathSum)=>{
        if(node ===null){
            // 结束点
            return 
        }
        if(!node.left && !node.right){
            if(pathSum === node.val){
                // 目标点
                paths.push([...path,node.val].slice())
            }
            // 结束点
            return
        }
        // 进左子树的时候记录位置
        path.push(node.val)
        // 开始点
        dfs(node.left,path,pathSum - node.val)
        dfs(node.right,path,pathSum - node.val)
        // 出右子树的时候删除位置
        path.pop()
    }
    dfs(root,[],targetSum)
    return paths
};