代码随想录Day18打卡 二叉树(5)

38 阅读1分钟

112 路径总和1

这道题不需要用到回溯,因为只需要走到叶子节点即可

var hasPathSum = function(root, targetSum) {
    const dfs = (node, currSum) => {
        if (!node) {
            return false
        }
        if (!node.left && !node.right) {
            if (currSum + node.val === targetSum) {
                return true
            } else {
                return false
            }
        }
        return dfs(node.left, currSum + node.val) || dfs(node.right, currSum + node.val)
    }
    return dfs(root, 0)
};

路径总和2

这道题需要回溯,因为我们要记录路径。

var pathSum = function(root, targetSum) {
    const res = [], path = []
    const dfs = (node, currSum) => {
        if (!node) {
            return 
        }
        if (!node.left && !node.right && currSum + node.val === targetSum) {
            path.push(node.val)
            res.push([...path])
            path.pop()
            return 
        } 
        path.push(node.val)
        dfs(node.left, currSum + node.val)
        dfs(node.right, currSum + node.val)
        path.pop()
    }

    dfs(root, 0)
    return res
};

106 从中序与后序遍历构造二叉树

分割了数组,比较清晰,但是可以用index进行优化

var buildTree = function (inorder, postorder) {
    if (inorder.length === 0 && postorder.length === 0) {
        return null
    }
    // find the last element in postorder
    const rootVal = postorder.pop()
    const root = new TreeNode(rootVal)

    // if root is a leaf node
    if (postorder.length === 0) {
        return root
    }

    // find the center
    let centerIndex
    for (let i = 0; i < inorder.length; i++) {
        if (inorder[i] === rootVal) {
            centerIndex = i
        }
    }

    const leftInorder = inorder.slice(0, centerIndex)
    const rightInorder = inorder.slice(centerIndex + 1, inorder.length)

    const leftPostorder = postorder.slice(0, leftInorder.length)
    const rightPostorder = postorder.slice(leftInorder.length, postorder.length)

    root.left = buildTree(leftInorder, leftPostorder)
    root.right = buildTree(rightInorder, rightPostorder)

    return root
};

105 从中序和前序遍历构造二叉树

类似的写法,不过在前序遍历中,中间的分割node是第一个element

const buildTree = function (preorder, inorder) {
    if (preorder.length === 0) {
        return null
    }
    const rootVal = preorder.shift()
    const root = new TreeNode(rootVal)
    if (preorder.length === 0) {
        return root
    }

    let index
    for (let i = 0; i < inorder.length; i++) {
        if (inorder[i] === rootVal) {
            index = i
        }
    }
    
    const inorderLeft = inorder.slice(0, index)
    const inorderRight = inorder.slice(index + 1, inorder.length)

    const preorderLeft = preorder.slice(0, inorderLeft.length)
    const preorderRight = preorder.slice(inorderLeft.length, preorder.length)

    root.left = buildTree(preorderLeft, inorderLeft)
    root.right = buildTree(preorderRight, inorderRight)
    return root
};