Skip to main content

112.js

/** ------------------------------------------------------------------------------
*
* 112. Path Sum
* Topics: Tree, Depth-First Search, Binary Tree
* https://leetcode.com/problems/path-sum/description/
*
------------------------------------------------------------------------------ */
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} targetSum
* @return {boolean}
*/
var hasPathSum = function (root, targetSum) {
if (!root) return false
if (!root.left && !root.right && targetSum === root.val) return true

return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val)
}

var hasPathSumBFS = function (root, targetSum) {
if (!root) return false
const queue = [[root, root.val]]

while (queue.length) {
const [node, sum] = queue.shift()
if (!node.left && !node.right && sum === targetSum) return true
if (node.left) queue.push([node.left, sum + node.left.val])
if (node.right) queue.push([node.right, sum + node.right.val])
}

return false
}

console.log(hasPathSum([5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], 22))
console.log(hasPathSumBFS([5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], 22))