题目
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.
大致意思
给你一个二叉树,和一个数字,判断是否从头到位的路径中,存在一条路径的和等于这个数字
解决方案
- 进行DFS遍历。依次讲sum - root.val 赋给递归函数的val.
 - 如果
root不存在,直接return false - 如果
root不存在left和right,说明他是叶子节点。如果root.val === sum的话返回true。 - 最后进行持续的遍历
 
源代码
var hasPathSum = function(root, sum) {
  if (!root) return false;
  if (!root.left && !root.right && root.val === sum) return true;
  return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val)
};