Solving Leetcode Interviews in Seconds with AI: Path Sum II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "113" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references. A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: [[5,4,11,2],[5,8,4,5]] Explanation: There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 Example 2: Input: root = [1,2,3], targetSum = 5 Output: [] Example 3: Input: root = [1,2], targetSum = 0 Output: [] Constraints: The number of nodes in the tree is in the range [0, 5000]. -1000 <= Node.val <= 1000 -1000 <= targetSum <= 1000
Explanation
Here's an efficient solution to the problem:
- Depth-First Search (DFS): Traverse the tree using DFS, exploring each possible path from the root to a leaf.
- Path Tracking: Maintain a list to track the current path being explored.
Sum Calculation: Keep track of the current path's sum as we traverse. When a leaf node is reached, check if the current sum equals the targetSum. If it does, add a copy of the current path to the result.
Time Complexity: O(N), where N is the number of nodes in the tree.
- Space Complexity: O(H), where H is the height of the tree (in the worst case, a skewed tree where H = N). This is due to the recursion stack and the space used to store the paths.
Code
from typing import List, Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
result = []
path = []
def dfs(node: Optional[TreeNode], current_sum: int):
if not node:
return
path.append(node.val)
current_sum += node.val
if not node.left and not node.right: # Leaf node
if current_sum == targetSum:
result.append(path.copy()) # Append a copy to avoid modification
else:
dfs(node.left, current_sum)
dfs(node.right, current_sum)
path.pop() # Backtrack
dfs(root, 0)
return result