/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ publicclassSolution{ publicintpathSum(TreeNode root, int sum){ if (root == null) return0; return helper(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); }
privateinthelper(TreeNode node, int sum){ if (node == null) return0; int result = 0; if (node.val == sum) { result++; } result += helper(node.left, sum - node.val); result += helper(node.right, sum - node.val); return result; } }