Data Structures & AlgorithmsModerateICPC regional · GATE CS top band
Rooted tree with root 0 and vertices 0 to 9; the edges are 0–1, 1–2, 2–3, 2–4, 2–5, 0–6, 2–7, 7–8, 3–9 (parent–child). Every edge has length 1. What is the distance between vertices 5 and 7 (number of edges on the path)?
- A. 3
- B. 2
- C. 0
- D. 6
Correct answer: B. 2
The path goes up to the lowest common ancestor 2, so the length is 3 + 3 − 2·2 = 2. Adding depths or taking their difference ignores the common ancestor.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Array A = [6, 24, 27, 0, 7, 23, 30, 19]. How many index pairs i < j satisfy (A[i] XOR A[j]) < 25? (A trie with subtree counts answers this…
- Tree with vertices 0 to 9, root 0, edges 0–1, 1–2, 1–3, 1–4, 3–5, 1–6, 2–7, 5–8, 4–9 (parent–child). Vertex weights (vertex:weight) 0:16…
- Points A(4,3), B(7,5), C(8,9), D(6,6), E(4,6) in the plane. The cost of joining two points is the Manhattan distance |x1−x2| + |y1−y2|…
- A trie keeps a counter at each node, and every word of the list W = ['bb', 'bba', 'aabc', 'ac', 'aba', 'bbc', 'aab', 'ac'] is inserted…
- Directed graph on vertices A, B, C, D, E, F with edges E→F, E→A, C→D, D→C, D→B, B→C, A→C, A→D, B→D (no weights). What is the number of…
- A binary tree with distinct letters has preorder CHEGDBFA and inorder HECFBADG. What is its postorder traversal (left, right, root)…