Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Depth-First Search

Path Sum II

medium

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

Given the root of a binary tree and an integer target, write a recursive function to find all root-to-leaf paths where the sum of all the values along the path sum to target.

Example 1:

1247451

Input:

[1,2,4,4,7,5,1]
target = 10

Output:

[[1,2,7],[1,4,5]] # [[1,4,5],[1,2,7]] is also accepted.

The paths are 1 -> 2 -> 7 and 1 -> 4 -> 5

Explanation

This problem is an extension of the Path Sum problem. In this problem, we are asked to return a list of all root-to-leaf paths where the sum of the nodes in the path equals a given target sum.
This is an example of a question which benefits from using a global variable that all recursive calls have access to store the list of all root-to-leaf paths that match the target sum.
Return Values In this case question, we don't need our recursive calls to return any values. Instead, we use depth-first search to traverse each root-to-leaf path in the tree, while maintaining the state of the current path via parameters to the recursive call.
Base Case We can stop recursing when our tree is empty.
Extra Work At each node, we need to add the value of the node to the current path.
Whenever we are at a leaf node, we can check if the value of the current node matches the target. If it does, we can add the current path to the global list of paths.
Helper Function Parent nodes need to pass two pieces of information down to their children:
  1. The remaining target sum
  2. The values along the current path (starting from the root).
These values must be passed down as parameters of the recursive call, so we need to introduce a helper function to help us recurse.
Global Variables We will use a global variable to store the root-to-leaf paths that match the given target. This allows us to avoid having to return path arrays up the recursion stack and simplifies collecting all valid paths.
Solution
Python
Language
def dfs(node, target, path):
# base case
if not node:
return
# append current value to the path
path.append(node.val)
if not node.left and not node.right:
if node.val == target:
result.append(path[:])
dfs(node.left, target - node.val, path)
dfs(node.right, target - node.val, path)
# when our code reaches here, are done exploring all
# the root-to-leaf paths that go through the current node.
# pop the current value from the path to prepare for the next path
path.pop()
Global Variables We can use a single global variable that all recursive calls have access to store the list of paths that add up to the target sum.

Solution

Solution
Python
Language
class Solution:
def pathSum(self, root, target):
def dfs(node, target, path):
# base case
if not node:
return
# append current value to the path
path.append(node.val)
if not node.left and not node.right:
if node.val == target:
result.append(path[:])
dfs(node.left, target - node.val, path)
dfs(node.right, target - node.val, path)
# when our code reaches here, are done exploring all
# the root-to-leaf paths that go through the current node.
# pop the current value from the path to prepare for the next path
path.pop()
result = []
dfs(root, target, [])
return result

Animated Solution

Visualization
Python
Language
Try these examples:
def pathSum(root, target):
def dfs(node, target, path):
if not node:
return
path.append(node.val)
if not node.left and not node.right:
if node.val == target:
result.append(path[:])
dfs(node.left, target - node.val, path)
dfs(node.right, target - node.val, path)
path.pop()
result = []
dfs(root, target, [])
return result
1247451

path sum II

0 / 41

Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(N²) where N is the number of nodes in the binary tree. We visit each node exactly once, which is O(N). However, when we find a valid root-to-leaf path, we copy it into the result list, which costs up to O(H) where H is the tree height. With K valid paths, the total copy cost is O(K·H), giving us O(N + K·H) overall. In the worst case: a 'caterpillar' tree where a long spine of N/2 nodes each has a leaf child — both K and H are O(N), so this becomes O(N²). Note that a fully balanced tree gives O(N·log N) since H = log N, and a fully skewed tree (a straight chain) gives O(N) since K = 1. The O(N²) worst case comes from tree shapes in between these extremes.

Space Complexity: O(N²) where N is the number of nodes in the binary tree in the worst case. The recursion stack uses O(H) space and the current path list uses O(H) space where H is the tree height. The result stores K valid paths of up to length H, which is O(K·H). In the worst case: the same 'caterpillar' tree shape would total to O(N²).

Mark as read

Next: Longest Univalue Path

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Explanation

Solution

Animated Solution

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress