[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)); } } } };
相关文章推荐
- javascript动态添加css样式
- [LeetCode][JavaScript]Path Sum
- Javascript在页面的执行顺序
- Angular.js学习笔记(一)
- 转载js入门须知
- JavaScript Core -- 理解闭包
- JavaScript Core -- 事件
- JavaScript BOM -- setTimeout()和setInterval() 常见问题
- IDF实验室之不难不易的js加密
- JavaScript Core -- 包装对象
- JavaScript Core -- 构造命名空间封装函数
- JavaScript Core -- 继承机制
- JavaScript Core -- 垃圾回收机制
- JavaScript Core -- 数组
- iframe中子父窗口互调的js方法
- js监听 window.open 关闭事件
- JSTL中的核心标签库(EL)
- JavaScript Core -- 不可小视的标点符号
- JavaScript Core -- 如何创建一个对象
- JSTL进阶之自定义标签