← Questions
Sum tree with node values computed from children
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Airbnb's coding round, last asked Sep 2025. It tests trees, caching and design.
You get a rooted tree. Each leaf holds an integer. Every internal node's value is the sum of its children's values, so it equals the sum of the leaves below it. Answer value queries fast, while the tree changes shape.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
SumTree(edges: list[tuple[str, str]], leaf_values: dict[str, int]): builds the tree from(parent, child)edges. -
get(node_id) -> int: the node's current value. -
to_leaf(node_id, value) -> None: removes the node's whole subtree below it and makes it a leaf withvalue. -
to_parent(node_id, edges, leaf_values) -> None: turns a leaf into an internal node by attaching a new subtree rooted at it. With no edges, it becomes an internal node with no children and value 0.
Example
root -> a, b; b -> c, d; leaves a = 4, c = 6, d = -1
get("root") -> 9
get("b") -> 5
to_leaf("b", 2)
get("root") -> 6
to_parent("a", [("a", "e"), ("a", "f"), ("f", "g")], {"e": 3, "g": 10})
get("a") -> 13
get("f") -> 10
get("root") -> 15
Constraints
- Up to
2 * 10^5nodes across the whole input; leaf values from-10^9to10^9, so sums need 64 bits. - Operations are valid:
to_parentis called on a current leaf, and new node IDs are not already in the tree. - The tree can be very deep.
Clarifying questions
- Are mutations frequent compared with queries?
- How deep can the tree get?
- What happens to the IDs of removed nodes: can they be reused later?
What a strong answer covers
- Store each node's subtree sum, parent pointer and children, so
getis O(1). - On a change, compute the delta at the changed node and add it to every ancestor: O(depth).
- Removing a subtree iteratively (explicit stack) and attaching one by computing its sums bottom-up before adding its total to the ancestors.
- Iteration instead of recursion everywhere, since the tree may be deep.
- When O(depth) is too slow (a path-shaped tree with many updates): Euler tour plus a Fenwick tree, or link-cut trees.
Follow-ups
- Add
set_leaf(node_id, value)for a leaf whose value changes. - Support moving a whole subtree under another parent.
- Return the sum over a node's subtree at a given depth only.
Where it's asked
- Airbnb · Coding · Last asked Sep 202545 min · Live coding, one or two rounds, from the same pool as the screen
What it tests
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
