A visualiser draws the outline of a binary tree as one continuous stroke: it starts at the root, runs down the left side, sweeps along the bottom through every leaf, and climbs back up the right side. You need the values in the order the pen meets them.
Each node is { val, left, right }, where left and right are nodes or null. The outline is defined as:
The root, first.
The left edge: start at root.left; from each node, move to its left child if it has one, otherwise to its right child. Stop before reaching a leaf. If the root has no left child, the left edge is empty.
The leaves: every node with no children, from left to right.
The right edge: the mirror image, starting at root.right and preferring the right child, listed from the bottom up. If the root has no right child, it is empty.
treeOutline(root, direction = "anticlockwise") returns the values in that order. With direction = "clockwise", it returns the same outline traced the other way: the root, then the right edge top-down, the leaves from right to left, and the left edge bottom-up.
Rules:
Every node appears at most once. A single node is both the root and a leaf, so the answer is [val].
null returns []. If root is neither null nor an object, throw a TypeError. A direction other than "anticlockwise" or "clockwise" throws a RangeError.
Trees can be 100,000 levels deep, so do not recurse.