Print Binary Tree

MediumArrayStringLinked ListTreeBinary TreeGraph

Description

Given root of a binary tree, return a 2D string representation of the tree with each level on a row, properly positioned.

Examples

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

Height 2 tree needs 3 columns. Root '1' at center, left child '2' at left position of next row.

Input:root = [1]
Output:[["1"]]
Explanation:

Edge case with a single-element array.

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

Binary tree with root 1, left child 2, right child 3, and node 2 has right child 4. The 2D representation shows the tree structure across 3 levels with proper spacing.

Constraints

  • 1 ≤ nodes ≤ 2¹⁰

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!