← Questions
All root-to-leaf path sums
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Dec 2025. It tests trees and dfs.
Given the root of a binary tree whose nodes hold integers (possibly negative), return a list with the sum of the values along every path from the root to a leaf. A leaf is a node with no children. List the sums in depth-first, left-to-right order of the leaves.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
path_sums(root: TreeNode | None) -> list[int]— an empty tree returns[].
Example
5
/ \
4 8
/ \
11 4
-> [9, 24, 17] # 5+4, 5+8+11, 5+8+4
single node -3 -> [-3]
empty tree -> []
Constraints
- Up to about
10^4nodes. - Values fit in a 32-bit signed integer; sums may need 64 bits in fixed-width languages.
Clarifying questions
- Is the order of the sums important?
- Can values be negative?
- What should an empty tree return?
- Is the tree deep enough to worry about recursion depth?
What a strong answer covers
- DFS that carries the running sum down and appends it when it reaches a node with no children.
- Treating a node with only one child correctly: it is not a leaf, so no sum is recorded there.
- An iterative version with a stack of
(node, sum)pairs, pushing the right child before the left to keep left-to-right order. -
O(n)time andO(h)extra space. - Tests: empty tree, single node, a skewed tree, negative values, nodes with one child.
Follow-ups
- Return the paths themselves, not only their sums.
- Return whether any path sums to a given target, or count the paths (starting anywhere, going down) that sum to it.
- Each node holds a digit; return the sum of the numbers the root-to-leaf paths spell.
Where it's asked
- Meta · AI-enabled coding · Last asked Dec 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
trees · dfs
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
