Graph Theory37 sections · 1633 units
Open in Course

Subtree Queries - Walkthrough

(Example execution)

I'll walk you through a complete example. Tree structure: node 11 (root) has children 22 and 33. Node 22 has child 44. Each node holds a value: 141 \to 4, 222 \to 2, 353 \to 5, 414 \to 1.

DFS visits nodes in order: 12431 \to 2 \to 4 \to 3. Entry times (when first visited): node 11 gets 00, node 22 gets 11, node 44 gets 22, node 33 gets 33. Exit times mark when you leave each subtree.

Flatten values by entry time into arr = [4, 2, 1, 5]. Node 22's subtree spans indices [1,3)[1, 3) in this array. Sum those positions: 2+1=32 + 1 = 3. Update node 44's value to 1010 by changing arr[2]. Now node 22's subtree sums to 1212.