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)
      return 0;
    return dfs(root, sum) +
           pathSum(root->left, sum) +
           pathSum(root->right, sum);
  }

 private:
  int dfs(TreeNode* root, int sum) {
    if (!root)
      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, sum: int) -> int:
    if not root:
      return 0

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

    return dfs(root, sum) + \
        self.pathSum(root.left, sum) + \
        self.pathSum(root.right, sum)
Back to top