给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
/**
* 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) {
if (!root) return []
var result = []
var hasPathSum = function(root, targetSum, history) {
if (!root) return false
if (!root.left && !root.right) {
if (root.val === targetSum) {
result.push(history)
return true
}
} else {
root.left && hasPathSum(root.left, targetSum - root.val, [...history, root.left.val])
root.right && hasPathSum(root.right, targetSum - root.val, [...history, root.right.val])
}
};
hasPathSum(root, targetSum, [root.val])
return result
};