Compress an n-ary tree by promoting children
I was asked this
No reports yet. Sign in to say where you were asked it.
Each node of an n-ary tree holds a unique integer value and an ordered list of children. You are given the root and a list compressed_nodes of values.
Implement compress(root, compressed_nodes) -> root. For every node whose value appears in the list, remove that node and promote its children: they take the removed node's place in its parent's child list, in their original order. The root is never compressed, even if its value is listed. Values that do not appear in the tree are ignored. A compressed node may have compressed descendants; their children move up as far as needed.
class Node:
val: int
children: list[Node]
Constraints
-
1 <= n <= 10^5nodes; the tree can be very deep (for example, a single path). -
0 <= len(compressed_nodes) <= n. - You may change the tree in place.
Example 1
Tree (each line is parent -> children):
10 -> [20, 30, 40]
20 -> [50, 60]
30 -> [70]
compress(root, [20]) returns:
10 -> [50, 60, 30, 40]
30 -> [70]
Node 20 is gone, and 50 and 60 take its place, before 30.
Example 2
Same starting tree, compress(root, [30, 70, 10]). Node 30 is removed, and so is its only child 70, a leaf, so nothing is promoted from that branch. 10 is the root, so it stays. Result:
10 -> [20, 40]
20 -> [50, 60]
Part 2: Return the height of the compressed tree (edges on the longest root-to-leaf path) without changing or rebuilding the tree.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.


