113 Path Sum 2 ****

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1
Return:

[
   [5,4,11,2],
   [5,8,4,5]
]
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }
        List<Integer> sub = new ArrayList<>();
        helper(root, sum, ans, sub);
        return ans;
    }
    public void helper(TreeNode root, int sum, List<List<Integer>> ans, List<Integer> sub) {
        if (root == null) {
            return;
        }
        sub.add(root.val);
        if(root.left == null && root.right == null) {
            if (sum == root.val) {
                ans.add(new ArrayList<Integer>(sub));
            }
        }
        helper(root.left, sum - root.val, ans, sub);
        helper(root.right, sum - root.val, ans, sub);
        sub.remove(sub.size() - 1);
    }
}

results matching ""

    No results matching ""