Enter a binary tree and an integer, and print out the sum of node values in the binary tree as all paths to the input integers.

A path starts at the root of the tree and goes all the way down to the nodes that pass through the leaves.

Give the binary tree as follows and give num=22. 5 / \ 4 June 12 13 6 / / / \ \ / \ 9 5 1 output: [,4,12,1 [5], [5,6,6,5]]Copy the code

code

/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; *} * /
/ * * *@param {TreeNode} root
 * @param {number} sum
 * @return {number[][]}* /
var findPath = function(root, sum) {
    const path = []
    const ans = []
    function dfs(root, sum) {
        if(! root)return
        path.push(root.val)
        sum -= root.val
        if(! root.left && ! root.right && ! sum) ans.push([...path]) dfs(root.left,sum) dfs(root.right,sum) path.pop() } dfs(root,sum)return ans
};
Copy the code