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 exists a root-to-leaf path 5->4->11->2 The sum is 22.
/** * Definition for a binary tree node. * public class TreeNode { * int val; return true; return hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val); } } This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:
Original author:Jake Tao,source:"112. Path Sum"