Problem 655

Abstract / Summary

Print a binary tree's nodes in a formatted way that shows its structure.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
25 lines | 785 bytes | submitted September 4, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.70 | σ = 1.05

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
32 links | 18 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

25 solutions   September 4, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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