Data Structures & AlgorithmsHardAmazon · Microsoft OA

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 inorder.

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 inorder.
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def ins(r, v):
    if not r: return T(v)
    if v < r.v: r.l = ins(r.l, v)
    else: r.r = ins(r.r, v)
    return r
root = None
for v in [5, 2, 13, 1, 4, 9]: root = ins(root, v)
acc = 0
def conv(n):
    global acc
    if not n: return
    conv(n.r); acc += n.v; n.v = acc; conv(n.l)
conv(root)
out = []
def ino(n):
    if n: ino(n.l); out.append(n.v); ino(n.r)
ino(root); print(out)
What is printed?
  1. A. [1, 3, 7, 12, 21, 34]
  2. B. [34, 33, 31, 27, 22, 13]
  3. C. [34, 32, 28, 23, 22, 13]
  4. D. [33, 31, 27, 22, 13, 9]

Correct answer: B. [34, 33, 31, 27, 22, 13]

Sorted keys 1, 2, 4, 5, 9, 13 (total 34). Going from largest down: 13 → 13, 9 → 22, 5 → 27, 4 → 31, 2 → 33, 1 → 34, so the inorder is [34, 33, 31, 27, 22, 13].

More Coding Interview Problems questions

Exams that ask this topic