[LeetCode][JavaScript]Path Sum
2015-10-11 16:45
507 查看
Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.For example:
Given the below binary tree and
sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path
5->4->11->2which sum is 22.
https://leetcode.com/problems/path-sum/
判断是否有一条从根到叶子的路径的和为sum。
如果不是叶子节点,递归进去,如果是叶子节点,计算路径是不是等于sum。
两道类似的题:
Binary Tree Paths : /article/7171000.html
Path Sum II : /article/7171042.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 {boolean} */ var hasPathSum = function(root, sum) { if(root && root.val !== undefined){ return hasSum(root, 0); } return false; function hasSum(node, value){ var isLeaf = true, tmp; if(node.left){ isLeaf = false; tmp = hasSum(node.left, value + node.val); if(tmp === true){ return true; } } if(node.right){ isLeaf = false; tmp = hasSum(node.right, value + node.val); if(tmp === true){ return true; } } if(isLeaf){ tmp = value + node.val; if(tmp === sum){ return true; } } return false; } };
相关文章推荐
- 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进阶之自定义标签
- Jsoup中getElementsByClass中className有空格处理
- JSON认识