Minimize Tree Height with K Cut & Attach-to-Root Operations

viaLeetCode

Problem: Given a rooted tree, in up to K operations you may: cut any subtree from its parent and attach it directly under the root. Minimize the height of the final tree and return that minimum height.

Constraints: Up to K operations; tree can be arbitrarily shaped/skewed initially.

Approach: Greedily target the deepest chains first: each operation can "hoist" one subtree to depth 1 under the root, effectively capping the depth contributed by that entire subtree to 1 + its own internal height. Sort candidate subtrees by how much height reduction each hoist buys, greedily apply up to K hoists to the subtrees yielding the largest reduction in overall tree height, and binary search on the final height combined with a feasibility check (can we bring the tree to height <= H using at most K hoists) for an efficient solution.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account