Tree Pretty Printer - Problem

Implement a function to display a binary tree in a visually readable format on the console with proper spacing and branch lines.

The output should show the tree structure with:

  • Node values displayed clearly
  • Branch connections using ASCII characters (|, -, +)
  • Proper indentation to show the tree levels
  • Left and right child positioning

For a null node, do not display anything at that position. The tree should be readable and maintain proper hierarchical structure.

Input & Output

Example 1 — Basic Binary Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: 3 / \ 9 20 / \ 15 7
💡 Note: Tree with root 3, left child 9, right child 20. Node 20 has children 15 and 7. Display shows proper indentation and branch connections.
Example 2 — Single Node
$ Input: root = [1]
Output: 1
💡 Note: Single node tree displays just the value with no connections needed.
Example 3 — Left-Heavy Tree
$ Input: root = [1,2,null,3,null]
Output: 1 / 2 | 3
💡 Note: Tree grows only to the left, showing vertical connections down the left side.

Constraints

  • The number of nodes in the tree is in the range [0, 2000]
  • -1000 ≤ Node.val ≤ 1000

Visualization

Tap to expand
INPUT TREE[3,9,20,null,null,15,7]3920157Tree Data StructureNodes with parent-childrelationshipsALGORITHM STEPS1Tree Traversal (BFS/DFS)Visit each node systematically2Calculate PositioningDetermine spacing and indentation3Format Each LevelBuild display strings with proper spacing4Add ConnectionsDraw ASCII branch lines (/, \, |)Processing Example:Level 0: root node (max indent)Level 1: children (less indent)Level 2: grandchildren (min indent)FORMATTED OUTPUTPretty Printed Tree: 3 / \ 9 20 / \ 15 7nullnull157✓ Visual Tree DisplayClear hierarchy withASCII branch connectionsProper indentation showstree structure levelsKey Insight:Tree pretty printing requires systematic traversal with calculated spacing - like drawing an org chart,each level needs proper indentation and ASCII connections to show parent-child relationships clearly.TutorialsPoint - Tree Pretty Printer | Level-Order Formatting
Asked in
Microsoft 15 Amazon 12 Google 8
23.0K Views
Medium Frequency
~30 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen