112.路径总和
function TreeNode(val, left, right) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
this.right = (right === undefined ? null : right)
}
var hasPathSum = function (root, targetSum) {
if (!root) {
return false
}
let sumQueue = []
let queue = []
queue.push(root)
sumQueue.push(root.val)
while (queue.length) {
let len = queue.length
for (let i = 0; i < len; i++) {
let node = queue.shift()
let sum = sumQueue.shift()
if (node.left === null && node.right === null) {
if (sum === targetSum) {
return true
}
}
if (node.left) {
queue.push(node.left)
sumQueue.push(sum + node.left.val)
}
if (node.right) {
queue.push(node.right)
sumQueue.push(sum + node.right.val)
}
}
}
return false
};
let root = new TreeNode(1)
console.log(hasPathSum(root, 1));
var hasPathSum = function (root, targetSum) {
if (root === null) {
return false
}
if (root.left == null && root.right === null && root.val === targetSum) {
return true
}
return hasPathSum(root.left, targetSum - root.val)
|| hasPathSum(root.right, targetSum - root.val)
}