Print a binary tree as aligned text
Company: Crusoe
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates competence in binary tree data structures, spatial layout and string formatting by requiring conversion of a hierarchical tree into a constrained ASCII representation with placeholder handling for missing children; domain: Coding & Algorithms.
Constraints
- 1 <= number of input entries; level_order[0] != "#" for a non-empty tree.
- Each present value is a single character with no spaces; "#" is reserved as the absent-node sentinel.
- Input list is in level-order (BFS) and only includes positions down to the deepest present node.
- Tree height h satisfies 2^(h-1) leaf slots fitting in memory (h is small in practice).
Examples
Input: ["A", "B", "C", "#", "D"]
Expected Output: [" A ", " B C ", "* D * *"]
Explanation: The prompt example. Height 3 -> 4 leaf slots. B has only a right child D, so its left leaf slot is '*'. C is missing both children -> '* *'. Parents B and C are centered above their child pairs, and A is centered above the whole row.
Input: ["A"]
Expected Output: ["A"]
Explanation: Single-node tree: height 1, one leaf slot, one line containing just the root.
Input: ["A", "B", "C"]
Expected Output: [" A ", "B C"]
Explanation: Full tree of height 2: 2 leaf slots 'B C' separated by one space, A centered above them.
Input: ["A", "B", "C", "D", "E", "F", "G"]
Expected Output: [" A ", " B C ", "D E F G"]
Explanation: A perfect tree of height 3. The leaf row 'D E F G' has each value one space apart; B sits above D/E and C above F/G; A is centered above all.
Input: ["A", "B", "#", "D"]
Expected Output: [" A ", " B * ", "D * * *"]
Explanation: A->B (A's right child is absent -> '*' in the upper-right). B->D (B's right child absent). Height 3, so the missing positions still occupy slots and print as '*'.
Input: ["A", "#", "C", "#", "F"]
Expected Output: [" A ", " * C ", "* * * F"]
Explanation: A has no left child ('*' on the left of the middle row) and a right child C; C has only a right child F (bottom-right slot). All absent positions render as '*'.
Input: []
Expected Output: []
Explanation: Empty input -> empty drawing.
Hints
- First rebuild the tree from the level-order array (skip a child when its value is "#"), then compute the height h.
- The bottom row is a full level with 2^(h-1) leaf slots; slot i sits at column 2*i, so the line is 2*2^(h-1) - 1 characters wide.
- Recurse positionally over a FULL tree: a node covering leaf slots [lo, hi] is drawn at the midpoint column (2*lo + 2*hi)/2; split into [lo, mid] and [mid+1, hi] for its children. Print '*' wherever the real node is missing.