Data Structures & AlgorithmsVery hardProduct-company placement
A tree on vertices 1–8 has edges 2–1, 3–1, 4–2, 5–2, 6–4, 7–5, 8–3. What is the sum of the distances (in edges) over all unordered pairs of vertices?
- A. 144
- B. 72
- C. 65
- D. 79
Correct answer: B. 72
Each edge splitting the tree into parts of sizes s and n − s lies on s·(n − s) of the paths; summing over the 7 edges gives 72. Counting ordered pairs would double it.
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
- Keys 64, 95, 22, 60, 55, 18, 69, 31, 78, 65, 26 are inserted in that order into an empty BST. Then 64 is deleted and after that 22 is…
- A 4 × 4 grid has rows 1 5 2 1 / 1 1 5 4 / 7 4 6 2 / 1 6 3 8. Moving only right or down from the top-left to the bottom-right cell, what is…
- How many calls of g (including the first) are made when g(7) is evaluated, and what value is returned? c int g(int n) { if (n <= 2) return…
- The words trie, tried, trip, try, tree are inserted into an empty trie (one node per character, shared prefixes share nodes, plus a root)…
- In the grid 21112 / 11110 / 10111 / 11111 (rows top to bottom; 2 = rotten, 1 = fresh, 0 = empty), every minute each rotten orange rots its…
- An undirected graph has edges A–E, A–H, B–F, C–E, C–G, D–G, D–H, E–F, E–G, F–H. BFS starts at A and always scans neighbours in…