bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 113. Path Sum II

113. Path Sum II

Leetcode Solutions

Depth First Search (DFS) with Backtracking

  1. Define a helper function dfs that takes the current node, the current path, and the remaining sum as arguments.
  2. If the current node is null, return immediately as this is not a valid path.
  3. Subtract the value of the current node from the remaining sum.
  4. Append the current node's value to the path.
  5. If the current node is a leaf (no children) and the remaining sum is 0, add the current path to the list of valid paths.
  6. Recursively call dfs on the left and right children of the current node, passing the updated path and remaining sum.
  7. After exploring both children, backtrack by removing the last element from the path to explore other potential paths.
  8. Call dfs with the root node, an empty path, and the target sum to start the DFS traversal.
  9. Return the list of valid paths after the traversal is complete.
UML Thumbnail

Breadth First Search (BFS) with Path Tracking

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...