Quick Overview

Build a string matrix that draws a binary tree, with the root centered in the top row and each child placed at a column offset that halves on every level. It tests computing tree height, deriving the grid size from it, and placing nodes with a depth-first or breadth-first walk.

Lay Out a Binary Tree as a Centered String Matrix

Company: Uber

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

Given the `root` of a binary tree, construct a 0-indexed `m x n` string matrix `res` that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules: - The height of the tree is `height` and the number of rows `m` should be equal to `height + 1`. - The number of columns `n` should be equal to `2^(height+1) - 1`. - Place the root node in the middle of the top row. - For each node at position `res[r][c]`, place its left child at `res[r+1][c - 2^(height-r-1)]` and its right child at `res[r+1][c + 2^(height-r-1)]`. Return the constructed matrix `res`. ### Function Signature ```python def print_tree(root: list[int | None]) -> list[list[str]]: ``` ### Rules - The tree arrives as a level-order list. `None` marks a missing child, children of a missing node are not listed, and trailing `None` values may be omitted. For example, `[1, 2, 3, None, 4]` is a root 1 with children 2 and 3, where 2 has only a right child 4. - Height counts edges on the longest root-to-leaf path, so a single node has height 0. - Each node's cell holds its value as a decimal string, such as `"7"` or `"-12"`. Every cell without a node holds the empty string `""`. ### Constraints - The number of nodes in the tree is between 1 and `2^10`. - `-99 <= Node.val <= 99` - The depth of the tree is between 1 and 10. ### Examples ```text Input: root = [1, 2] Output: [ ["", "1", ""], ["2", "", ""] ] ``` The height is 1, so the matrix is 2 x 3. The root goes to (0, 1), and its left child goes one column left of it, `2^(1-0-1) = 1`, at (1, 0). ```text Input: root = [1, 2, 3, None, 4] Output: [ ["", "", "", "1", "", "", ""], ["", "2", "", "", "", "3", ""], ["", "", "4", "", "", "", ""] ] ``` The height is 2, so the matrix is 3 x 7. The root sits at (0, 3), its children are 2 columns away at (1, 1) and (1, 5), and node 4, the right child of 2, is 1 column right of it at (2, 2). ```text Input: root = [1, None, -2, None, 3] Output: [ ["", "", "", "1", "", "", ""], ["", "", "", "", "", "-2", ""], ["", "", "", "", "", "", "3"] ] ``` The tree is a chain of right children, so the height is 2 and the matrix is again 3 x 7. Node -2 lands at (1, 5) and node 3 at (2, 6), the last column.

Overview: Build a string matrix that draws a binary tree, with the root centered in the top row and each child placed at a column offset that halves on every level. It tests computing tree height, deriving the grid size from it, and placing nodes with a depth-first or breadth-first walk.

Given a binary tree, build a 0-indexed `m x n` string matrix `res` that draws the tree using these rules: - Let `height` be the height of the tree. Height counts edges on the longest root-to-leaf path, so a single node has height 0. - The number of rows is `m = height + 1`. - The number of columns is `n = 2^(height+1) - 1`. - The root goes in the middle of the top row. - For a node placed at `res[r][c]`, its left child goes at `res[r+1][c - 2^(height-r-1)]` and its right child goes at `res[r+1][c + 2^(height-r-1)]`. - A cell that holds a node contains that node's value as a decimal string, such as `"7"` or `"-12"`. Every cell without a node holds the empty string `""`. Return the matrix `res` as a list of rows, top row first, each row listing its cells from column 0 to column n - 1. ### Input format The tree arrives as `root`, a level-order list of integers and `None` (`null` in JavaScript and Java, `std::nullopt` in C++). The first entry is the root. After it, the entries give the left child and then the right child of each node that exists, taken in level order. `None` marks a missing child, the children of a missing node are not listed, and trailing `None` values may be omitted. For example, `[1, 2, 3, None, 4]` is a root 1 with children 2 and 3, where 2 has only a right child 4. ### Example 1 Input: root = [1, 2] Output: [ ["", "1", ""], ["2", "", ""] ] The height is 1, so the matrix is 2 x 3. The root goes to (0, 1), and its left child goes 2^(1-0-1) = 1 column to the left, at (1, 0). ### Example 2 Input: root = [1, 2, 3, None, 4] Output: [ ["", "", "", "1", "", "", ""], ["", "2", "", "", "", "3", ""], ["", "", "4", "", "", "", ""] ] The height is 2, so the matrix is 3 x 7. The root sits at (0, 3), its children are 2 columns away at (1, 1) and (1, 5), and node 4, the right child of 2, is 1 column to the right of it at (2, 2). ### Constraints - The number of nodes in the tree is between 1 and 2^10. - -99 <= Node.val <= 99 - The depth of the tree is between 1 and 10. - `root` is a valid level-order encoding as described above, and its first entry is never `None`. - Every number involved, including the matrix dimensions and indices, fits in a 32-bit signed integer; none can exceed 2^31 - 1.

Constraints

  • The number of nodes in the tree is between 1 and 2^10.
  • -99 <= Node.val <= 99
  • The depth of the tree is between 1 and 10.
  • root is a valid level-order encoding: its first entry is the root value (never None), None marks a missing child, the children of a missing node are not listed, and trailing None values may be omitted.
  • Every number involved, including the matrix dimensions and indices, fits in a 32-bit signed integer; none can exceed 2^31 - 1.

Examples

Input: ([1, 2],)

Expected Output: [['', '1', ''], ['2', '', '']]

Explanation: Source example 1: height 1 gives a 2 x 3 matrix and the left child sits 2^0 = 1 column left of the root.

Input: ([1, 2, 3, None, 4],)

Expected Output: [['', '', '', '1', '', '', ''], ['', '2', '', '', '', '3', ''], ['', '', '4', '', '', '', '']]

Explanation: Source example 2: 3 x 7 matrix; 4 is the right child of a left child and lands at (2, 2) with the last-row offset 1.

Hints

  1. The matrix size and every column offset depend on the tree's height, so find the height before placing anything.
  2. When rebuilding the tree from the list, a missing node has no child entries, so pair list entries only with nodes that exist.
  3. A child's column comes from its parent's column and the parent's row, so filling the matrix from the top row down means each parent is placed before its children.

Draw a Binary Tree in a String Matrix

mediumUberSoftware Engineer

Given a binary tree, build a 0-indexed m x n string matrix res that draws the tree using these rules:

  • Let height be the height of the tree. Height counts edges on the longest root-to-leaf path, so a single node has height 0.
  • The number of rows is m = height + 1.
  • The number of columns is n = 2^(height+1) - 1.
  • The root goes in the middle of the top row.
  • For a node placed at res[r][c], its left child goes at res[r+1][c - 2^(height-r-1)] and its right child goes at res[r+1][c + 2^(height-r-1)].
  • A cell that holds a node contains that node's value as a decimal string, such as "7" or "-12". Every cell without a node holds the empty string "".

Return the matrix res as a list of rows, top row first, each row listing its cells from column 0 to column n - 1.

Input format

The tree arrives as root, a level-order list of integers and None (null in JavaScript and Java, std::nullopt in C++). The first entry is the root. After it, the entries give the left child and then the right child of each node that exists, taken in level order. None marks a missing child, the children of a missing node are not listed, and trailing None values may be omitted. For example, [1, 2, 3, None, 4] is a root 1 with children 2 and 3, where 2 has only a right child 4.

Example 1

Input: root = [1, 2] Output: [ ["", "1", ""], ["2", "", ""] ]

The height is 1, so the matrix is 2 x 3. The root goes to (0, 1), and its left child goes 2^(1-0-1) = 1 column to the left, at (1, 0).

Example 2

Input: root = [1, 2, 3, None, 4] Output: [ ["", "", "", "1", "", "", ""], ["", "2", "", "", "", "3", ""], ["", "", "4", "", "", "", ""] ]

The height is 2, so the matrix is 3 x 7. The root sits at (0, 3), its children are 2 columns away at (1, 1) and (1, 5), and node 4, the right child of 2, is 1 column to the right of it at (2, 2).

Constraints

  • The number of nodes in the tree is between 1 and 2^10.
  • -99 <= Node.val <= 99
  • The depth of the tree is between 1 and 10.
  • root is a valid level-order encoding as described above, and its first entry is never None.
  • Every number involved, including the matrix dimensions and indices, fits in a 32-bit signed integer; none can exceed 2^31 - 1.

Examples

Example 1
Input
([1, 2],)
Output
[['', '1', ''], ['2', '', '']]
Notes
Source example 1: height 1 gives a 2 x 3 matrix and the left child sits 2^0 = 1 column left of the root.
Example 2
Input
([1, 2, 3, None, 4],)
Output
[['', '', '', '1', '', '', ''], ['', '2', '', '', '', '3', ''], ['', '', '4', '', '', '', '']]
Notes
Source example 2: 3 x 7 matrix; 4 is the right child of a left child and lands at (2, 2) with the last-row offset 1.

Constraints

  • •The number of nodes in the tree is between 1 and 2^10.
  • •-99 <= Node.val <= 99
  • •The depth of the tree is between 1 and 10.
  • •root is a valid level-order encoding: its first entry is the root value (never None), None marks a missing child, the children of a missing node are not listed, and trailing None values may be omitted.
  • •Every number involved, including the matrix dimensions and indices, fits in a 32-bit signed integer; none can exceed 2^31 - 1.

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def print_tree(root: list[int | None]) -> list[list[str]]:
Sample call
print_tree([1, 2])
Language
Case 1
Input
([1, 2],)
Expected
[['', '1', ''], ['2', '', '']]
Case 2
Input
([1, 2, 3, None, 4],)
Expected
[['', '', '', '1', '', '', ''], ['', '2', '', '', '', '3', ''], ['', '', '4', '', '', '', '']]

Browse More Questions

Show the approach

Approach

Rebuild the tree from the level-order list with a pointer that walks the existing nodes in the order they were created. Each existing node takes the next two list entries as its left and right child, a None entry creates nothing, and the walk stops when the list runs out, so omitted trailing None values need no special handling. Nodes are numbered in creation order, which is breadth-first order, so every parent is numbered before its children. One pass in that order gives each child depth = parent depth + 1, and the largest depth is the height in edges. Then allocate height + 1 rows of 2^(height+1) - 1 empty strings, put the root at column 2^height - 1 (the middle of the top row), and make a second pass in the same order: write each node's value as a decimal string into its cell and give its children columns c - 2^(height-r-1) and c + 2^(height-r-1). Because parents come first, a node's column is always known when the pass reaches it. Correctness: the rules fix every cell, so following them exactly yields the only valid matrix. The offsets below the root add up to at most 2^(height-1) + ... + 1 = 2^height - 1, so every column stays inside 0..n-1, and two different nodes never share a cell because the sequence of left and right turns from the root determines the column. Edge cases: a single node gives a 1 x 1 matrix holding its value; a node valued 0 is a real node, not a missing one; explicit trailing None entries change nothing; the height comes from the deepest actual node, not from the length of the list.

Time complexity:
O(N + m * n), where N is the length of root and m x n is the matrix size (at most 10 x 1023)
Space complexity:
O(m * n) for the output matrix plus O(N) for the rebuilt tree