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?
  1. A. [1, 2, 4, 7, 8, 9, 10, 6, 3]
  2. B. [1, 2, 4, 7, 8, 9, 10, 3]
  3. C. [1, 2, 4, 5, 7, 8, 9, 10, 6, 3]
  4. 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

Exams that ask this topic