Data Structures & AlgorithmsModerateTCS NQT · Infosys
Problem: A rooted tree has root 1 and children: 1→2 (weight 4), 1→3 (weight 1), 2→4 (weight 2), 2→5 (weight 7), 3→6 (weight 3). The weighted depth of a node is the sum of edge weights from the root. What is the sum of the weighted depths of the leaves (nodes with no children)?
- A. 26
- B. 21
- C. 6
- D. 11
Correct answer: B. 21
Leaves 4, 5 and 6 have weighted depths 4 + 2 = 6, 4 + 7 = 11 and 1 + 3 = 4, so the sum is 21. Summing over all non-root nodes adds 4 and 1 (26), using unweighted depths gives 2 + 2 + 2 = 6, and taking only the deepest leaf gives 11.
More Coding Interview Problems questions
- Problem: A rooted binary tree stored as a parent array over nodes 0–9: parent of node i is [-1, 0, 0, 1, 1, 2, 3, 3, 4, 5][i] (node 0 is…
- Problem: A rooted tree of 8 nodes (root 1) is given by children lists: 1: [2, 3], 2: [4, 5], 3: [6], 4: [], 5: [7, 8], 6: [], 7: [], 8…
- Problem: The house-robber rule applies on a tree: you pick a set of nodes with no parent–child pair both chosen, maximising the total…
- Problem: The Z-function of a string s is defined as z[i] = the length of the longest common prefix of s and s[i:]; z[0] is conventionally…
- Problem: Count the distinct non-empty substrings of "abcabc" (two substrings are the same if their letters are identical, regardless of…
- Problem: How many windows of length 3 in the text "bacacbaab" are anagrams of the pattern "aab" (same letters with the same…