Path sum III

It's a good example of double DFS in the brute force implementation

class Solution {
  public int pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return 0;
        }
        return 
        dfs(root, targetSum, 0) 
        + pathSum(root.left, targetSum) 
        + pathSum(root.right, targetSum);
    }

    private int dfs(TreeNode node, int targetSum, long sum) {
        if (node == null) {
            return 0;
        }
        sum += node.val;
        int count = sum == targetSum ? 1 : 0;
        count += dfs(node.left, targetSum, sum);
        count += dfs(node.right, targetSum, sum);
        return count;
    }
}

Where we can use pre-sum to change it to one layer DFS, to optimize the algorithm from O(n2) to O(n)

Last updated