This is an upgrade version from 112. Path Sum. For that question, we have the solution as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13
publicbooleanhasPathSum(TreeNode root, int sum){ if (root == null) { returnfalse; }
// reach leave node if (root.left == null && root.right == null && sum == root.val) { returntrue; }
// check left tree and right tree return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); }
Here we need an ans variable to hold all the results. A temp variable to hold the traversed path. The thing to note is that the list in java is passed by reference, so after the recursion, you must delete the previously added elements without affecting the temp of other branches.