Path Sum
Description
doc
Solutions
Recursive Version
/**
* 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
}
const leftTarget = targetSum - root.val
if (!leftTarget && !root.left && !root.right) {
return true
}
return hasPathSum(root.left, leftTarget) || hasPathSum(root.right, leftTarget)
}
- Time Complexity: O(n)
- Space Complexity: O(1)
DFS
/**
* 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
}
const queue = [root]
while (queue.length) {
const cur = queue.shift()
const left = targetSum - cur.val
if (!left && !cur.left && !cur.right) {
return true
}
if (cur.left) {
cur.left.val += cur.val // try to make it immutable in prod
queue.push(cur.left)
}
if (cur.right) {
cur.right.val += cur.val
queue.push(cur.right)
}
}
return false
}
- Time Complexity: O(n)
- Space Complexity: O(log(n)) ? maybe