Print Binary Tree

MediumTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a non-empty binary tree, lay it out on a grid of strings and return the grid. Let h be the height of the tree, counted in **edges** on the longest root-to-leaf path (a single node has height 0). The grid has h + 1 rows and 2^(h+1) - 1 columns, and every cell starts as the empty string "". Place the root in row 0 at the middle column (cols - 1) / 2. If a node sits at row r, column c, its left child goes to row r + 1, column c - 2^(h-r-1), and its right child to row r + 1, column c + 2^(h-r-1). Each placed cell holds the node's value written as a decimal string (for example "-7"). Missing children leave their cells empty.

Examples

Input: root = [4,7]
Output: [["","4",""],["7","",""]]
Height 1 gives 2 rows and 3 columns. The root sits in column 1 and its left child one column to the left.
Input: root = [8,-3,5,null,6]
Output: [["","","","8","","",""],["","-3","","","","5",""],["","","6","","","",""]]
Height 2 gives a 3 x 7 grid. The root is at column 3, its children are 2 columns away, and 6 (right child of -3) is 1 column right of column 1.

Constraints

  • 1 <= number of nodes <= 2^10
  • The height of the tree is at most 9
  • -99 <= Node.val <= 99

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems