Looking for some help on optimizing solution to this problem
You are given the root of a binary tree and a target integer k.
The height of a tree is defined as the number of nodes on the longest path from the root to any leaf.
You can perform an operation on any node: "delete" it. A "deleted" node is not removed from the tree structure. Instead, it is bypassed when calculating the height. For any given root-to-leaf path, the number of deleted nodes on that path is not counted towards its length.
For example, on a path A -> B -> C, the height is 3. If node B is "deleted", the path for height calculation becomes A -> C, and its new length is 2.
Your Goal:
Find a set of nodes to delete such that the new height of the tree is at most .
Optimization:
You must find a solution that uses the minimum possible number of deletions.
Tie-Breaker:
If there are multiple sets of nodes that all achieve this minimum count, you must return the set that prioritizes deleting nodes at a greater depth (farther from the root). Formally, you must return the set that maximizes the sum of the depths of the deleted nodes, where depth(root) = 1.
Return a set containing the TreeNode objects that should be deleted.
Input:
A (1)
/
B (2)
/
C (3)k = 2
Original Height: 3 (path A->B->C)
Possible Solutions (min count = 1):
Output: {C}
Explanation: All three options achieve the minimum deletion count of 1. We apply the tie-breaker and choose the set with the maximum sum of depths. {C} has a sum of 3, which is the highest.
Input:
A (1)
/ \
B (2) C (2)
/ \
D (3) E (3)k = 2
Original Height: 3 (paths A->B->D and A->C->E)
Possible Solutions:
Output: {A}
Explanation: The primary goal is to find the minimum number of deletions. Option 1 achieves the goal with 1 deletion, while the others require 2. The tie-breaker rule is not applied because the minimum counts are not equal.
Input:
A (1)
/
B (2)
/ \
C D
(3) (3)k = 2
Original Height: 3 (paths A->B->C and A->B->D)
Possible Solutions:
Output: {B}
Explanation: Both {A} and {B} achieve the minimum deletion count of 1. We apply the tie-breaker: sum_depths({B}) = 2 is greater than sum_depths({A}) = 1.