Data Structures & AlgorithmsVery hardProduct company OA
What is the diameter (largest distance between any two nodes) of the weighted tree with edges 1–2 (3), 1–3 (4), 2–4 (2), 2–5 (6), 3–6 (5), 6–7 (1)? (Two DFS passes: farthest from any node, then farthest from that.)
- A. 16
- B. 19
- C. 13
- D. 21
Correct answer: B. 19
From 1 the distances are 2: 3, 3: 4, 4: 5, 5: 9, 6: 9, 7: 10, so the first pass ends at 7. From 7 the farthest node is 5: 7–6–3–1–2–5 = 1 + 5 + 4 + 3 + 6 = 19, the diameter. Stopping after the first pass reports only 10; the path with the most edges is not automatically the heaviest one.
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
- Running median with two heaps (a max-heap for the lower half, a min-heap for the upper half, sizes differing by at most 1, the lower half…
- Each array is a binary tree in level order (0-indexed, children at 2i + 1 and 2i + 2, all positions present). Which one is a valid BST?
- Binary trees with node labels A, B, C have preorder A B C and postorder C B A. How many different binary trees match BOTH traversals?
- An alien language uses only the letters a, b, c, d. The words bca, bcd, ad, ac, dc are listed in sorted order. Building an edge from each…
- What is the maximum flow from S to T in the network with capacities S→A 10, S→B 5, A→B 15, A→T 6, B→T 10?
- Weighted undirected graph: A–B 1, B–C 2, C–A 2, C–D 1, B–D 2. How many DIFFERENT minimum spanning trees does it have?