LeetCode Solutions

113. Path Sum II

Time: $O(n\log n)$

Space: $O(n)$

			

class Solution {
 public:
  vector<vector<int>> pathSum(TreeNode* root, int sum) {
    vector<vector<int>> ans;
    dfs(root, sum, {}, ans);
    return ans;
  }

 private:
  void dfs(TreeNode* root, int sum, vector<int>&& path,
           vector<vector<int>>& ans) {
    if (root == nullptr)
      return;
    if (root->val == sum && root->left == nullptr && root->right == nullptr) {
      path.push_back(root->val);
      ans.push_back(path);
      path.pop_back();
      return;
    }

    path.push_back(root->val);
    dfs(root->left, sum - root->val, move(path), ans);
    dfs(root->right, sum - root->val, move(path), ans);
    path.pop_back();
  }
};
			

class Solution {
  public List<List<Integer>> pathSum(TreeNode root, int sum) {
    List<List<Integer>> ans = new ArrayList<>();
    dfs(root, sum, new ArrayList<>(), ans);
    return ans;
  }

  private void dfs(TreeNode root, int sum, List<Integer> path, List<List<Integer>> ans) {
    if (root == null)
      return;
    if (root.val == sum && root.left == null && root.right == null) {
      path.add(root.val);
      ans.add(new ArrayList<>(path));
      path.remove(path.size() - 1);
      return;
    }

    path.add(root.val);
    dfs(root.left, sum - root.val, path, ans);
    dfs(root.right, sum - root.val, path, ans);
    path.remove(path.size() - 1);
  }
}
			

class Solution:
  def pathSum(self, root: TreeNode, summ: int) -> List[List[int]]:
    ans = []

    def dfs(root: TreeNode, summ: int, path: List[int]) -> None:
      if not root:
        return
      if root.val == summ and not root.left and not root.right:
        ans.append(path + [root.val])
        return

      dfs(root.left, summ - root.val, path + [root.val])
      dfs(root.right, summ - root.val, path + [root.val])

    dfs(root, summ, [])
    return ans