Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such this 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 / / / 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/
Determines if there is a path from the root to the leaf and is sum.
If it is not a leaf node, recursively go in, if it is a leaf node, the calculation path is not equal to sum.
Two similar questions:
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} rootTen * @param {number} sum One * @return {Boolean} A */ - varHaspathsum =function(root, sum) { - if(Root && root.val!==undefined) { the returnHassum (Root, 0); - } - return false; - + functionhassum (node, value) { - varIsLeaf =true, TMP; + if(node.left) { AIsLeaf =false; atTMP = Hassum (node.left, Value +node.val); - if(TMP = = =true){ - return true; - } - } - if(node.right) { inIsLeaf =false; -TMP = Hassum (node.right, Value +node.val); to if(TMP = = =true){ + return true; - } the } * if(isleaf) { $TMP = value +Node.val;Panax Notoginseng if(TMP = = =sum) { - return true; the } + } A return false; the } +};
[Leetcode] [JavaScript] Path Sum