码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Path Sum II

时间:2015-10-11 18:05:57      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

 

[LeetCode][JavaScript]Path Sum II

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4869538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!