#655

Print Binary Tree

specialist · 675 · lc medium +30 · verified · 66.4% accepted · 564 likes · top 72%

Description

Given the root of a binary tree of height h, lay it out in an (h+1) x (2^(h+1) - 1) string matrix. Place the root at the midpoint of the top row; recursively place each node's left child offset left and right child offset right by half the remaining column span. Fill all empty cells with "". Return the resulting matrix.

Example 1:

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

Example 2:

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

Code

1
2
3
4
5
6
7
8
9