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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code