Subtree Totals Under Collapse and Graft Operations
Data Structure DesignAuto-graded · 17 test casesLast updated
Maintain per-node totals in a rooted tree while nodes are collapsed into leaves or have a subtree grafted onto a leaf, answering total queries after each change.
You are given a rooted tree in which every node has a unique integer id. A node is described by a dictionary with the keys "id", "value" and "children" (a list of node dictionaries, possibly empty or missing).
- A node with no children is a leaf, and its own
"value"is its total. - A node with at least one child is internal. Its
"value"field is ignored, and its total is the sum of the totals of its direct children.
You must process a sequence of commands against this tree and report results. Commands are given as two parallel lists, operations and arguments; arguments[i] holds the arguments for operations[i].
| Operation | Arguments | Effect | Result |
|---|---|---|---|
"getValue" | [node_id] | Report the current total of that node. | the integer total |
"toLeaf" | [node_id, value] | The node becomes a leaf with total value. All of its descendants are removed from the tree. If it was already a leaf, only its value changes. | None |
"toParent" | [node_id, subtree] | The node, which is currently a leaf, becomes an internal node whose only child is the root of subtree (a node dictionary in the same format as above, with ids not present in the tree). The node's total becomes the total of that subtree root. | None |
Totals of all ancestors must reflect every change, so that any later getValue returns the correct total for the current shape of the tree. Applying the commands to the root itself is allowed.
Return a list with one entry per operation, in order: an integer for getValue, and None for toLeaf and toParent.
Implement sum_tree_session(initial_tree, operations, arguments).
Constraints
- All ids, including those in grafted subtrees, are unique across the tree at any moment.
- Values are integers and may be negative or zero.
getValueis only called on ids that currently exist.toParentis only called on a node that is currently a leaf.- A node dictionary may omit
"children"or give an empty list; both mean leaf. - Reads should be fast: aim for far less work per query than recomputing a subtree sum.
Examples
Example 1
Input: sum_tree_session({'id': 1, 'value': 0, 'children': [{'id': 2, 'value': 3, 'children': []}, {'id': 3, 'value': 0, 'children': [{'id': 4, 'value': 5, 'children': []}, {'id': 5, 'value': -1, 'children': []}]}]}, ['getValue', 'getValue', 'toLeaf', 'getValue', 'toParent', 'getValue', 'getValue'], [[1], [3], [3, 7], [1], [3, {'id': 6, 'value': 0, 'children': [{'id': 7, 'value': 2, 'children': []}, {'id': 8, 'value': 4, 'children': []}]}], [1], [3]])
Output: [7, 4, None, 10, None, 9, 6]
Example 2
Input: sum_tree_session({'id': 10, 'value': 4, 'children': []}, ['getValue', 'toParent', 'getValue', 'toLeaf', 'getValue'], [[10], [10, {'id': 11, 'value': 0, 'children': [{'id': 12, 'value': -2, 'children': []}]}], [10], [10, 0], [10]])
Output: [4, None, -2, None, 0]
Hints
Hint 1
If you store the total of every node, a query becomes a single lookup. The work moves into the commands that change the tree.
Hint 2
When one node's total changes by some delta, each of its ancestors changes by exactly that delta and nothing else changes. Keep parent pointers so you can walk upward.
Hint 3
When collapsing a node into a leaf, delete all descendants from your maps so no stale entries remain. When grafting, load the new subtree bottom-up so its totals are computed before you attach it.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store the total of every node, not only the leaves. Then getValue is one dictionary lookup. The cost moves into the two mutations.
Keep three dictionaries keyed by node id:
parent[id]: the parent id, orNonefor the root.children[id]: the list of child ids.totals[id]: the current total of the node.
Loading a tree. A post-order traversal records parent and children links and computes totals: a leaf takes its own value, an internal node takes the sum of its children's totals. Post-order guarantees children are finished before their parent.
getValue. Return totals[id].
toLeaf(id, value).
- Remember the old total.
- Delete every descendant from all three dictionaries, so no stale ids remain.
- Clear the child list and set the total to
value. - Add
value - oldto every ancestor by walking parent pointers.
toParent(id, subtree).
- Remember the old total.
- Load the subtree with the node as its parent; this returns the subtree root's total.
- Make the subtree root the node's only child and set the node's total to that value.
- Add
new - oldto every ancestor.
Why it is correct
The invariant is that every internal node's total equals the sum of its children's totals. Loading establishes it bottom-up. When a node's total changes by delta, each ancestor has exactly one child on the path to that node, so its sum changes by exactly delta. Nodes off that path keep unchanged children. Added nodes satisfy the invariant by construction, and removed nodes are discarded entirely. Adding delta along the ancestor path therefore restores the invariant everywhere.
Complexity
Let d be the depth of the mutated node and k the number of nodes removed or added.
- Build: O(n) time.
getValue: O(1).toLeafandtoParent: O(k + d). Each node is created once and removed at most once, so subtree work is amortized against total input size; only the upward walk of lengthdis not.- Space: O(n) for the maps, plus recursion depth proportional to tree height.
Very deep trees could exceed Python's recursion limit in the recursive helpers; an explicit stack would avoid that. For deep trees with many updates, an Euler tour with a Fenwick tree or a link-cut tree could cut the update cost to O(log n), at the price of complexity and losing O(1) reads.
Reference solution
from typing import Dict, List, Optional
def sum_tree_session(initial_tree: Dict, operations: List[str], arguments: List[List]) -> List[Optional[int]]:
parent = {}
children = {}
totals = {}
def load(node, parent_id):
node_id = node["id"]
parent[node_id] = parent_id
child_nodes = node.get("children", []) or []
children[node_id] = [c["id"] for c in child_nodes]
for c in child_nodes:
load(c, node_id)
if child_nodes:
totals[node_id] = sum(totals[c["id"]] for c in child_nodes)
else:
totals[node_id] = node["value"]
return totals[node_id]
def remove(node_id):
for c in children[node_id]:
remove(c)
del parent[node_id]
del children[node_id]
del totals[node_id]
def push_up(node_id, delta):
while node_id is not None:
totals[node_id] += delta
node_id = parent[node_id]
load(initial_tree, None)
results = []
for op, args in zip(operations, arguments):
if op == "getValue":
results.append(totals[args[0]])
elif op == "toLeaf":
node_id, value = args
old = totals[node_id]
for c in list(children[node_id]):
remove(c)
children[node_id] = []
totals[node_id] = value
push_up(parent[node_id], value - old)
results.append(None)
elif op == "toParent":
node_id, subtree = args
old = totals[node_id]
new = load(subtree, node_id)
children[node_id] = [subtree["id"]]
totals[node_id] = new
push_up(parent[node_id], new - old)
results.append(None)
return results