Skip to content

437. Path Sum III 👍

  • Time: $O(n\log n) \to O(n^2)$
  • Space: $O(\log n) \to O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int pathSum(TreeNode* root, int sum) {
    if (root == nullptr)
      return 0;
    return dfs(root, sum) +            //
           pathSum(root->left, sum) +  //
           pathSum(root->right, sum);
  }

 private:
  int dfs(TreeNode* root, int sum) {
    if (root == nullptr)
      return 0;
    return (sum == root->val) +                //
           dfs(root->left, sum - root->val) +  //
           dfs(root->right, sum - root->val);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int pathSum(TreeNode root, int sum) {
    if (root == null)
      return 0;
    return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
  }

  private int dfs(TreeNode root, int sum) {
    if (root == null)
      return 0;
    return (sum == root.val ? 1 : 0) +   //
        dfs(root.left, sum - root.val) + //
        dfs(root.right, sum - root.val);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def pathSum(self, root: TreeNode | None, summ: int) -> int:
    if not root:
      return 0

    def dfs(root: TreeNode, summ: int) -> int:
      if not root:
        return 0
      return (int(summ == root.val) +
              dfs(root.left, summ - root.val) +
              dfs(root.right, summ - root.val))

    return (dfs(root, summ) +
            self.pathSum(root.left, summ) +
            self.pathSum(root.right, summ))