113 Path Sum II

113. Path Sum II

1. Question

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For 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]
]

2. Implementation

(1) Backtracking

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        getPathSum(root, 0, sum, path, res);
        return res;
    }

    public void getPathSum(TreeNode node, int depth, int sum, List<Integer> path, List<List<Integer>> res) {
        if (node == null) {
            return;
        }

        path.add(node.val);

        if (node.left == null && node.right == null && node.val == sum) {
            res.add(new ArrayList(path));
        }

        getPathSum(node.left, depth + 1, sum - node.val, path, res);
        getPathSum(node.right, depth + 1, sum - node.val, path, res);

        path.remove(path.size() - 1);
    }
}

3. Time & Space Complexity

Backtracking:

Last updated