给定二叉树,确定是否存在从根节点到叶节点的所有路径和等于给定sum
递归实现,当二叉树左右节点为空且值等于sum时为true,faster than 29%
/**
* 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 === null)
return false
if(root.left === null && root.right === null && sum === root.val)
return true
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val)
};