Skip to the code
cf.
+25 XP

#340 Remove a Tag From the Tag Tree

medium

A notes app stores tag ids in a binary search tree with unique values. When a user deletes a tag, its node must be removed while keeping the search tree rule.

Write removeTag(root, tag) that removes the node with value tag and returns the new root. Use exactly these rules so the result is unique:

  • If the node has no children, remove it. If it has one child, that child takes its place.
  • If it has two children, find the smallest value in its right subtree (the successor), copy that value into the node, then remove the successor from the right subtree using these same rules.
  • If tag isn't in the tree, return the tree unchanged.

Example 1

Input: root = [50,30,70,20,40,60,80], tag = 30
Output: [50,40,70,20,null,60,80]

30 has two children. Its successor is 40, which is copied up; then the old 40 leaf is removed.

Example 2

Input: root = [50,30,70,20], tag = 30
Output: [50,20,70]

30 has one child, 20, which takes its place.

Constraints

  • 0 <= number of tags <= 10000
  • Tag ids are unique.

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).