Bea.AI coding blog
  • Tree
    • Tree Traverse
    • Iteration based traverse
    • Typical problems and solutions
      • Max width of binary tree
      • Binary Tree & BST Serialize & Deserialize
      • Lowest common ancestor (LCA) for Binary Tree and BST
      • Subproblem-based Approach for Resolving Max Value on Trees
      • Path sum III
  • Graph
  • Data structure
    • Java data structure
  • Algorithm general templates
    • Tree
    • Trie
    • Graph
  • Java Algorithm Tips and Tricks
    • Java concurrent list
  • Coding patterns & Strategies
  • Coding patterns & template
    • 1. Binary Search
    • 2. Two Pointer
    • 3. Sliding Window
    • 4. Backtracking
    • 5. DFS
    • 6. BFS
    • 7. Stack
    • 8. Heap
    • 9. Prefix Sum
    • 10. Linked List
    • 11. BST
    • 12. Line sweep
    • 14. Tree
    • 15. Graph
    • 16. Bit manipulation
    • 17. Matrix
    • 18. Monotonic Stack
    • 19. Sorting
    • 20. Union Find
    • 21. Trie
    • 22. Dynamic programming
    • 23. Customized Data Structure
  • Code interview steps
  • Leetcode
    • Tree
      • Traversal
      • Construction and Conversion
      • Search and Validation
      • Manipulation and Modification
      • Special Trees
      • Miscellaneous
    • Dynamic programing
      • Classic DP Problems
      • Sequence/Array DP
      • Matrix DP
      • Knapsack Problems
      • String DP
      • Tree/Graph DP
      • Optimization Problems
      • Combinatorial DP
    • DFS
      • Graph Traversal
      • Path Finding
      • Tree Traversal
      • Backtracking
      • Topological Sorting
      • Traversal Order
      • Dynamic Programming with DFS
      • Connected Components
    • BFS
      • Graph
      • Tree
      • Matrix
      • String
      • Others
    • Two points
      • Array
      • String
      • Linked List
      • Sorting
      • Others
    • LinkedList
      • Basic Operations
      • Cycle Detection and Handling
      • Intersection and Union
      • Partitioning and Merging
      • Palindrome
      • Miscellaneous
    • Backtracking
    • Binary Search
    • Union Find
    • Trie
    • Sort
    • Heap
    • Randomness
    • Topological sort
    • Stack
    • HashTable
    • Sliding Window
  • Blind 75
    • Array
    • Binary
    • Dynamic Programming
    • Graph
    • Interval
    • LinkedList
    • Matrix
    • String
    • Tree
    • Heap
  • Companies
    • Apple
Powered by GitBook
On this page
  1. Tree
  2. Typical problems and solutions

Path sum III

PreviousSubproblem-based Approach for Resolving Max Value on TreesNextGraph

Last updated 2 years ago

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)

class Solution {
  int count = 0;
  public int pathSum(TreeNode root, int targetSum) {
         Map<Long, Integer> sumCounterMap = new HashMap<>();
        sumCounterMap.put(0L, 1);
        dfs(root, targetSum, 0L, sumCounterMap);
        return count;
    }

    private void dfs(TreeNode node, int targetSum, long curSum, 
        Map<Long, Integer> sumCounterMap) {
        if (node == null) {
            return;
        }
        curSum += node.val;
        if (sumCounterMap.containsKey(curSum-targetSum)) {
            count += sumCounterMap.get(curSum-targetSum);
        }
        sumCounterMap.put(curSum, sumCounterMap.getOrDefault(curSum, 0) + 1);
        dfs(node.left, targetSum, curSum, sumCounterMap);
        dfs(node.right, targetSum, curSum, sumCounterMap);
        sumCounterMap.put(curSum, sumCounterMap.get(curSum) - 1);
    }
}
Path Sum III - LeetCodeLeetCode
Logo