call(back)
Algorithms & Data StructuresmediumSign in to star problems

Boundary of a Full Binary Tree

A binary tree is full: every node has either two children or none. Return its boundary anti-clockwise, starting at the root: the left edge from the root down to the leftmost leaf's parent, then every leaf from left to right, then the right edge from the rightmost leaf's parent back up to the root's right child. No node appears twice, and a lone root is its own boundary. Trees arrive in level order with null for missing children.

boundary([1, 2, 3, 4, 5, 6, 7])          ->  [1, 2, 4, 5, 6, 7, 3]
boundary([1, 2, 3, null, null, 6, 7])    ->  [1, 2, 6, 7, 3]        // 2 is a leaf, so the left edge is just the root
boundary([1])                            ->  [1]

Hints

Hint 1

Full means a node that is not a leaf always has both children, so each edge is a straight walk: keep going left (or right) until the next node is a leaf.

Hint 2

Three passes — the left edge without its leaf, every leaf left to right, the right edge without its leaf in reverse — and the single-node tree handled before any of them.

Topics

Asked at

Similar Problems6