> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Print Binary Tree Python Solution with Tests

> Tested Python solution for LeetCode 655 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 655, [Medium](/catalog/medium). Topics: [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/print-binary-tree/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 655   # by problem number
lcpy gen -s print_binary_tree   # by problem name
```

## Problem

Given the `root` of a binary tree, construct a **0-indexed** `m x n` string matrix `res` that represents a **formatted layout** of the tree. The formatted layout matrix should be constructed using the following rules:

* The **height** of the tree is `height` and the number of rows `m` should be equal to `height + 1`.
* The number of columns `n` should be equal to `2^height+1^ - 1`.
* Place the **root node** in the **middle** of the **top row** (more formally, at location `res[0][(n-1)/2]`).
* For each node that has been placed in the matrix at position `res[r][c]`, place its **left child** at `res[r+1][c-2^height-r-1^]` and its **right child** at `res[r+1][c+2^height-r-1^]`.
* Continue this process until all the nodes in the tree have been placed.
* Any empty cells should contain the empty string `""`.

Return the constructed matrix `res`.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/05/03/print1-tree.jpg)

```
Input: root = [1,2]
Output: [['','1',''],['2','','']]
```

![Example 2](https://assets.leetcode.com/uploads/2021/05/03/print2-tree.jpg)

```
Input: root = [1,2,3,null,4]
Output: [['','','','1','','',''],['','2','','','','3',''],['','','4','','','','']]
```

### Constraints

* The number of nodes in the tree is in the range `[1, 2^10]`.
* `-99 <= Node.val <= 99`
* The depth of the tree will be in the range `[1, 10]`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/print_binary_tree/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/print_binary_tree/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Solution:
    # Time: O(n + m * n) where n is the number of nodes and m is the tree height
    # Space: O(m * n) for the result matrix
    def print_tree(self, root: TreeNode[int] | None) -> list[list[str]]:
        def height(node: TreeNode[int] | None) -> int:
            if node is None:
                return -1
            return 1 + max(height(node.left), height(node.right))

        h = height(root)
        rows, cols = h + 1, 2 ** (h + 1) - 1
        res: list[list[str]] = [[""] * cols for _ in range(rows)]
        if root is None:
            return res

        def place(node: TreeNode[int] | None, r: int, c: int) -> None:
            if node is None:
                return
            res[r][c] = str(node.val)
            place(node.left, r + 1, c - 2 ** (h - r - 1))
            place(node.right, r + 1, c + 2 ** (h - r - 1))

        place(root, 0, (cols - 1) // 2)
        return res
```

## Complexity

| Time | Space |
| - | - |
| O(n + m \* n) where n is the number of nodes and m is the tree height | O(m \* n) for the result matrix |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.