Skip to main content
Back to problems
#655
Medium Algorithms

Print binary tree

Tree Depth-First Search Breadth-First Search Binary Tree
66.4% acceptance
Feb 20, 2026
563
469
Given the root of a binary tree, construct a 0-indexed m x n string matrix such that the root of the tree is at row 0, column (n-1)/2, and each node is placed according to the tree structure rules described.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn print_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<String>> {
    fn height(node: &Option<Rc<RefCell<TreeNode>>>) -> usize {
      match node {
        None => 0,
        Some(n) => {
          let b = n.borrow();
          1 + height(&b.left).max(height(&b.right))
        }
      }
    }
    let h = height(&root);
    let cols = (1 << h) - 1;
    let mut grid = vec![vec!["".to_string(); cols]; h];
    fn fill(
      node: &Option<Rc<RefCell<TreeNode>>>,
      grid: &mut Vec<Vec<String>>,
      row: usize,
      left: usize,
      right: usize,
    ) {
      if let Some(n) = node {
        let mid = (left + right) / 2;
        let b = n.borrow();
        grid[row][mid] = b.val.to_string();
        fill(&b.left, grid, row + 1, left, mid.saturating_sub(1));
        fill(&b.right, grid, row + 1, mid + 1, right);
      }
    }
    fill(&root, &mut grid, 0, 0, cols - 1);
    grid
  }
}