113. Path Sum II(js)

113. 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.

Note: A leaf is a node with no children.

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]
]
题意:找出所有路径,使得路径值的和等于sum
代码如下:
/**
 * 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 pathSum = function(root, sum) {
    let left,right;
    if(!root) return [];
    if(root.val===sum && root.left==null && root.right==null) return [[root.val]];
    left=pathSum(root.left,sum-root.val);
    right=pathSum(root.right,sum-root.val);
    
    for(let i=0;i<left.length;i++){
        left[i].unshift(root.val);
    }
    for(let i=0;i<right.length;i++){
        right[i].unshift(root.val);
    }
    return left.concat(right);
};

 

posted @ 2019-04-21 22:02  mingL  阅读(128)  评论(0编辑  收藏  举报