NewProject Coding is here — build features and fix bugs in real codebases with an AI assistantSee what's new

Given an N-ary tree where each node has an integer id and a list of children, calculate the maximum height of the tree after removing certain nodes. When a node is deleted, its children are promoted and connected directly to the deleted node's parent, similar to removing a node from a linked list while maintaining the chain.

The tree height is defined as the number of nodes on the longest path from the root to any leaf node. The root node will never be deleted, and a single-node tree has height 1.

Constraints:

  • 1 ≤ number of nodes ≤ 10410^4
  • Node IDs are unique integers
  • All ids in deletedIds exist in the tree
  • The root node is not in deletedIds

Example 1:

Input: deletedIds = [2]

    1
  / | \
 2  3  4
/ \
5  6

Output: 2 Explanation: After deleting node 2, its children 5 and 6 are promoted to become direct children of node 1. The tree becomes:

     1
  / | | \
 5  6 3  4

The longest path is from node 1 to any of its children, so the height is 2.

Example 2:

Input: deletedIds = []

1
|
2
|
3
|
4

Output: 4

Example 3:

Input: deletedIds = [3]

  1
  |
  2
 / \
3   4

Output: 3


Accepted
3.5k/4.8k
Acceptance Rate73.0%
Stdout
-