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->2
which sum is 22.
https://leetcode.com/problems/path-sum/
判断是否有一条从根到叶子的路径的和为sum。
如果不是叶子节点,递归进去,如果是叶子节点,计算路径是不是等于sum。
两道类似的题:
Binary Tree Paths : http://www.cnblogs.com/Liok3187/p/4735368.html
Path Sum II : http://www.cnblogs.com/Liok3187/p/4869538.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 {boolean} 12 */ 13 var hasPathSum = function(root, sum) { 14 if(root && root.val !== undefined){ 15 return hasSum(root, 0); 16 } 17 return false; 18 19 function hasSum(node, value){ 20 var isLeaf = true, tmp; 21 if(node.left){ 22 isLeaf = false; 23 tmp = hasSum(node.left, value + node.val); 24 if(tmp === true){ 25 return true; 26 } 27 } 28 if(node.right){ 29 isLeaf = false; 30 tmp = hasSum(node.right, value + node.val); 31 if(tmp === true){ 32 return true; 33 } 34 } 35 if(isLeaf){ 36 tmp = value + node.val; 37 if(tmp === sum){ 38 return true; 39 } 40 } 41 return false; 42 } 43 };