您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Path Sum II

2015-10-11 16:53 591 查看

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 : /article/7171000.html

Path Sum : /article/7171041.html

/**
* 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) {
var res = [];
if(root && root.val !== undefined){
getPathSum(root, [], 0);
}
return res;

function getPathSum(node, path, value){
var isLeaf = true, tmp;
if(node.left){
isLeaf = false;
getPathSum(node.left, path.concat(node.val), value + node.val);
}
if(node.right){
isLeaf = false;
getPathSum(node.right, path.concat(node.val), value + node.val);
}
if(isLeaf){
tmp = value + node.val;
if(tmp === sum){
res.push(path.concat(node.val));
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: