
js
/**
* 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 {number[][]}
*/
var pathSum = function (root, targetSum) {
const path = []
const ans = []
let val = 0
const backTracking = (node) => {
if (node === null) {
return
}
val += node.val
path.push(node.val)
if (node.left === null && node.right === null) {
if (val === targetSum) {
ans.push([...path])
}
} else {
backTracking(node.left)
backTracking(node.right)
}
// ⚠️以上要用if else写,不然的话叶子节点也要执行pop操作
val -= node.val
path.pop()
}
backTracking(root)
return ans
}