Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Delete the nodes with given values from a binary tree and return the roots of the remaining forest, sorted.

Problem: Delete the nodes with given values from a binary tree and return the roots of the remaining forest, sorted.
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):
    nodes = [T(x) if x is not None else None for x in xs]
    kids = iter(nodes[1:])
    for nd in nodes:
        if nd:
            nd.l = next(kids, None); nd.r = next(kids, None)
    return nodes[0]
def forest(root, dele):
    dele, roots = set(dele), []
    def go(nd, is_root):
        if not nd: return None
        gone = nd.v in dele
        if is_root and not gone: roots.append(nd.v)
        nd.l = go(nd.l, gone); nd.r = go(nd.r, gone)
        return None if gone else nd
    go(root, True)
    return sorted(roots)
print(forest(build([1, 2, 3, 4, 5, 6, 7, 8, 9]), [2, 3, 9]))
What is printed?
  1. A. [1, 4, 5]
  2. B. [1, 4, 5, 6, 7, 8]
  3. C. [4, 5, 6, 7]
  4. D. [1, 4, 5, 6, 7]

Correct answer: D. [1, 4, 5, 6, 7]

Deleting 2 frees its children 4 and 5; deleting 3 frees 6 and 7; 9 (a child of 4) simply disappears, while 8 stays attached to 4. Roots: 1, 4, 5, 6, 7.

More Coding Interview Problems questions

Exams that ask this topic