Data Structures & AlgorithmsVery hardProduct company OA
What is the maximum path sum in this binary tree, where a path joins any two nodes along parent–child links and need not pass through the root? Tree (parent: left, right): −10: 9, 20; 20: 15, 7; 9: −4, 6; 15: −2, –.
- A. 42
- B. 40
- C. 35
- D. 57
Correct answer: A. 42
For each node compute gain = value + the better non-negative child gain, and try value + both child gains as a path peak. At 20: 15 + 20 + 7 = 42. Through the root: 15 + 20 − 10 + (9 + 6) = 40, which is worse because −10 costs more than it connects. '57' adds every positive node, which is not a single path.
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 trie over 4-bit numbers finds the maximum XOR of any pair from [3, 10, 5, 9, 2, 8]. What is the maximum XOR?
- In a binary tree whose root is at level 0, what is the maximum number of nodes at level 5?
- A simple directed graph (no self-loops, at most one edge from u to v) has 6 vertices. What is the maximum number of edges?
- Which algorithm finds shortest paths (by number of edges) from one source in an UNWEIGHTED graph in O(V + E) time?
- A binary tree is stored in level order in a 0-indexed array (children of i at 2i + 1 and 2i + 2; None = no node): [1, 2, 3, None, 4, 5]…
- The minimum is deleted from the min-heap [2, 5, 3, 9, 6, 4, 8] (0-indexed): the last element moves to the root and sifts down, swapping…