Graph Theory37 sections · 1633 units
Open in Course

Walkthrough

(Sample queries)

Tree Structure:

 0 (root)
 / \
 1 2
 / \
 3 4

parent=[1,0,0,1,1]parent = [-1, 0, 0, 1, 1] means: node 00 has no parent (root), nodes 11 and 22 have parent 00, nodes 33 and 44 have parent 11.


Query 11: getKthAncestor(3,1)getKthAncestor(3, 1). Find the 11st ancestor of node 33

  • k=1=012k = 1 = 01_2 (binary), bit 00 is set
  • Jump 20=12^0 = 1 step: node = up[3][0] = 1
  • Result: 11 (parent of 33)

Query 22: getKthAncestor(3,2)getKthAncestor(3, 2). Find the 22nd ancestor of node 33

  • k=2=102k = 2 = 10_2 (binary), bit 11 is set
  • Jump 21=22^1 = 2 steps: node = up[3][1] = 0
  • Result: 00 (grandparent of 33)

Query 33: getKthAncestor(3,3)getKthAncestor(3, 3). Find the 33rd ancestor of node 33

  • k=3=112k = 3 = 11_2 (binary), bits 00 and 11 are set
  • Jump 20=12^0 = 1 step: node = up[3][0] = 1
  • Jump 21=22^1 = 2 steps: node = up[1][1] = -1 (no such ancestor)
  • Result: 1-1 (node 33 doesn't have a 33rd ancestor)