Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #655: Print Binary Tree

In this guide, we solve Leetcode #655 Print Binary Tree in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Tree, Depth-First Search, Breadth-First Search, Binary Tree

Intuition

We need to explore a structure deeply before backing up, which suits DFS.

DFS keeps local context on the call stack and is easy to implement recursively.

Approach

Define a recursive DFS that carries the necessary state.

Combine child results as the recursion unwinds.

Steps:

  • Define a recursive DFS with state.
  • Visit children and combine results.
  • Return the final aggregation.

Example

Input: root = [1,2] Output: [["","1",""],  ["2","",""]]

Python Solution

# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def printTree(self, root: Optional[TreeNode]) -> List[List[str]]: def height(root): if root is None: return -1 return 1 + max(height(root.left), height(root.right)) def dfs(root, r, c): if root is None: return ans[r][c] = str(root.val) dfs(root.left, r + 1, c - 2 ** (h - r - 1)) dfs(root.right, r + 1, c + 2 ** (h - r - 1)) h = height(root) m, n = h + 1, 2 ** (h + 1) - 1 ans = [[""] * n for _ in range(m)] dfs(root, 0, (n - 1) // 2) return ans

Complexity

The time complexity is O(V+E). The space complexity is O(V).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy