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?- A. [1, 4, 5]
- B. [1, 4, 5, 6, 7, 8]
- C. [4, 5, 6, 7]
- 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
- Problem: Print the boundary of a binary tree anticlockwise: root, left boundary (excluding leaves), all leaves left to right, then the…
- Problem: Convert a BST so each node's value becomes the sum of all values ≥ it (reverse inorder with a running sum); print the new…
- Problem: Count subtrees in which every node has the same value. python class T: def init(s, v): s.v, s.l, s.r = v, None, None def…
- Problem: Rain falls on a 2-D height map. Compute the trapped water volume with a min-heap that grows inward from the border. python import…
- Problem: Remove the fewest DISTINCT values so that at least half of the array's elements are removed (greedy on frequencies). python from…
- Problem: Find a target's index in a rotated sorted array of distinct values in O(log n). python def search(a, t): lo, hi = 0, len(a) - 1…