Python 0655.py
class Solution:
def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:
def getHeight(node):
if node:
return 1 + max(getHeight(node.left), getHeight(node.right))
else:
return -1
height = getHeight(root)
rows = height + 1
columns = 2**(height + 1) - 1
result = []
for i in range(rows):
result.append([ "" ] * columns)
def deeper(node, x, y):
if node:
result[y][x] = str(node.val)
step = 2**(height - y - 1)
deeper(node.left, x - step, y + 1)
deeper(node.right, x + step, y + 1)
deeper(root, columns // 2, 0)
return result
Difficulty
and has an acceptance rate of about 67% (100k+ submissions).
Typical patterns to solve this problem:
- Binary Tree
- Breadth First Search
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation builds a two-dimensional string matrix that visualizes a binary tree. Each node’s value appears centered in its row, and the horizontal spacing reflects the tree’s structure. The algorithm proceeds in three logical phases: computing the tree height, allocating a matrix of appropriate size, and recursively placing node values into the matrix.
Height Calculation
A helper function determines the maximum depth of the tree. It treats a missing child as contributing -1 to the height, so a leaf node yields a height of 0. The recursion explores both left and right sub-trees, selecting the larger depth and adding one for the current node.
def getHeight(node):
if node:
return 1 + max(getHeight(node.left), getHeight(node.right))
else:
return -1
The returned height drives the dimensions of the output matrix.
Grid Initialization
Using the computed height, the code derives the number of rows (height + 1) and columns (2**(height + 1) - 1). The column count follows the pattern of a full binary tree, guaranteeing enough space for every possible node position. An empty matrix is created by appending a list of empty strings for each row.
height = getHeight(root)
rows = height + 1
columns = 2**(height + 1) - 1
result = []
for i in range(rows):
result.append([ "" ] * columns)
This pre-allocation avoids dynamic resizing during the placement phase.
Depth-First Placement
A second recursive helper, deeper, walks the tree in a top-down manner. For each visited node, it writes the node’s value (converted to a string) into the matrix at coordinates (x, y). The horizontal offset for child nodes is computed as 2**(height - y - 1), which halves the step size with each descending level, preserving the visual symmetry of a full binary tree.
def deeper(node, x, y):
if node:
result[y][x] = str(node.val)
step = 2**(height - y - 1)
deeper(node.left, x - step, y + 1)
deeper(node.right, x + step, y + 1)
The initial call positions the root at the central column (columns // 2) and the top row (y = 0). The recursion naturally terminates when a None child is encountered.
Edge Cases Handled
When the input tree is empty (root is None), getHeight returns -1. Consequently, rows becomes 0 and columns becomes 0, yielding an empty result list. The subsequent call to deeper receives a None node and performs no assignments, so the function returns an empty matrix, correctly representing an empty tree.
For a single-node tree, the height is 0, producing a matrix of size 1 × 1. The root is placed at position (0, 0), and the recursion stops after processing both None children, resulting in a matrix containing only the root’s value.
The algorithm also gracefully handles highly unbalanced trees. Because the column count is based on the maximum possible width of a full tree of the same height, even a degenerate chain of left or right children fits within the pre-allocated matrix without index errors.
Performance Optimizations
The implementation minimizes overhead by calculating the matrix dimensions once, based on the tree height, and allocating the entire structure up front. This avoids repeated list growth operations during node insertion. The step size for horizontal positioning is derived using a power-of-two expression, which is a constant-time arithmetic operation, ensuring that each recursive call computes its child positions efficiently. Direct index assignment (result[y][x] = ...) eliminates the need for string concatenation or intermediate data structures, leading to fast in-place updates. The recursion depth matches the tree height, and each node is visited exactly once, providing a tight traversal without redundant work.
ELI5 - Simplified Explanation
Imagine a big empty grid that looks like a giant piece of graph paper. The goal is to draw a tree structure on this paper so every branch has its own special spot.
First, the code figures out how tall the tree is. Knowing the height helps define exactly how many rows and columns are needed so everything fits perfectly without bumping into anything else. A grid of empty strings is created, which is just like having a blank page waiting for labels.
Then, there is a helpful little helper function that walks through the tree starting from the very top. It takes the value sitting inside each spot of the tree and writes it into the correct box on the grid. To make sure the branches look even, it calculates a specific distance to move left or right before visiting the next branch. It does this over and over again, bouncing down the tree until every single piece of information is placed in its home on the grid.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| haoel | Python | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| haoel | Python | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 292: Nim Game
- problem 572: Subtree of Another Tree
- problem 617: Merge Two Binary Trees
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 213: House Robber II
- problem 237: Delete Node in a Linked List
- problem 260: Single Number III
- problem 416: Partition Equal Subset Sum
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 560: Subarray Sum Equals K
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 669: Trim a Binary Search Tree
- problem 687: Longest Univalue Path
- problem 1115: Print FooBar Alternately
- problem 1116: Print Zero Even Odd
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality