Data Structures & AlgorithmsModerateGATE CS · ICPC regional
Rooted tree with root 0 and vertices 0 to 9; the edges are 0–1, 1–2, 1–3, 0–4, 2–5, 5–6, 1–7, 2–8, 6–9 (parent–child). Every edge has length 1. What is the distance between vertices 7 and 2 (number of edges on the path)?
- A. 3
- B. 4
- C. 2
- D. 0
Correct answer: C. 2
The path goes up to the lowest common ancestor 1, so the length is 2 + 2 − 2·1 = 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
- A binary tree with distinct letters has preorder ABEDCF and inorder ECDFBA. What is its postorder traversal (left, right, root), written…
- Directed acyclic graph on vertices A, B, C, D, E, F (every edge goes from a smaller to a larger letter) with weighted edges A→D (9), A→E…
- Points A(3,7), B(3,5), C(9,0), D(8,2), E(5,4), F(5,6) in the plane. The cost of joining two points is the Manhattan distance |x1−x2| +…
- A trie keeps a counter at each node, and every word of the list W = ['b', 'abb', 'cbb', 'abc', 'ca', 'ca', 'aacc', 'b'] is inserted once…
- Directed acyclic graph on vertices A, B, C, D, E, F (every edge goes from a smaller to a larger letter) with weighted edges A→D (7), A→E…
- Undirected weighted graph on vertices A, B, C, D, E with edges A–B (1), A–C (3), A–E (1), B–C (2), B–D (3), C–E (3), D–E (3). An edge is…