Data Structures19 sections · 729 units
Open in Course

Example: Building a Tree

Step by step links

Build tree: 1-2, 1-3, 2-4, 2-5

// Initial: 5 separate nodes
link(2, 1)  // 2's parent = 1
link(3, 1)  // 3's parent = 1
link(4, 2)  // 4's parent = 2
link(5, 2)  // 5's parent = 2

Tree structure:

    1
   / \
  2   3
 / \
4   5

Now query path 4 to 3:

makeRoot(4)  // 4 becomes root
access(3)    // Path 4-2-1-3 in one aux tree
return aggregate of path

The path goes: 4 → 2 → 1 → 3 with length 4 (or sum of values).