[LeetCode][JavaScript]Path Sum II

Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             / 
            4   8
           /   / 
          11  13  4
         /      / 
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]
https://leetcode.com/problems/path-sum-ii/

求出所有等于sum的从根到叶子的路径。

还是跟上两题一样的思路。

Binary Tree Paths : http://www.cnblogs.com/Liok3187/p/4735368.html

Path Sum : http://www.cnblogs.com/Liok3187/p/4869521.html

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @param {number} sum
11  * @return {number[][]}
12  */
13 var pathSum = function(root, sum) {
14     var res = [];
15     if(root && root.val !== undefined){
16         getPathSum(root, [], 0);
17     }
18     return res;
19 
20     function getPathSum(node, path, value){
21         var isLeaf = true, tmp;
22         if(node.left){
23             isLeaf = false;
24             getPathSum(node.left, path.concat(node.val), value + node.val);
25         }
26         if(node.right){
27             isLeaf = false;
28             getPathSum(node.right, path.concat(node.val), value + node.val);
29         }
30         if(isLeaf){
31             tmp = value + node.val;
32             if(tmp === sum){
33                 res.push(path.concat(node.val));
34             }
35         }
36     }
37 };
原文地址:https://www.cnblogs.com/Liok3187/p/4869538.html