Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: Print the boundary of a binary tree anticlockwise: root, left boundary (excluding leaves), all leaves left to right, then the right boundary bottom-up (excluding leaves).
Problem: Print the boundary of a binary tree anticlockwise: root, left boundary (excluding leaves), all leaves left to right, then the right boundary bottom-up (excluding leaves).
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 boundary(root):
def leaf(n): return n and not n.l and not n.r
out = [root.v]
n = root.l
while n:
if not leaf(n): out.append(n.v)
n = n.l or n.r
def leaves(n):
if not n: return
if leaf(n) and n is not root: out.append(n.v)
leaves(n.l); leaves(n.r)
leaves(root)
st, n = [], root.r
while n:
if not leaf(n): st.append(n.v)
n = n.r or n.l
return out + st[::-1]
print(boundary(build([1, 2, 3, 4, 5, 6, None, None, None, 7, 8, 9, 10])))What is printed?- A. [1, 2, 4, 7, 8, 9, 10, 6, 3]
- B. [1, 2, 4, 7, 8, 9, 10, 3]
- C. [1, 2, 4, 5, 7, 8, 9, 10, 6, 3]
- D. [1, 2, 4, 7, 8, 9, 10, 6, 3, 5]
Correct answer: A. [1, 2, 4, 7, 8, 9, 10, 6, 3]
Left boundary: 1, 2 (4 is a leaf). Leaves left to right: 4, 7, 8 (children of 5), 9, 10 (children of 6). Right boundary goes 3 → 6 (no right child of 3, so it continues left) and is printed bottom-up: 6, 3. Node 5 is neither boundary nor leaf.
More Coding Interview Problems questions
- 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…
- Problem: You take trains in order; train i covers dist[i] km at a common integer speed, and every train except the last departs only at an…