Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.
Move from brute-force thinking to an efficient approach using tree strategy.
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:
height and the number of rows m should be equal to height + 1.n should be equal to 2height+1 - 1.res[0][(n-1)/2]).res[r][c], place its left child at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1]."".Return the constructed matrix res.
Example 1:
Input: root = [1,2] Output: [["","1",""], ["2","",""]]
Example 2:
Input: root = [1,2,3,null,4] Output: [["","","","1","","",""], ["","2","","","","3",""], ["","","4","","","",""]]
Constraints:
[1, 210].-99 <= Node.val <= 99[1, 10].Problem summary: 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 2height+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-2height-r-1] and its right child at res[r+1][c+2height-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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Tree
[1,2]
[1,2,3,null,4]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #655: Print Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<String>> printTree(TreeNode root) {
int h = height(root);
int m = h + 1, n = (1 << (h + 1)) - 1;
String[][] res = new String[m][n];
for (int i = 0; i < m; ++i) {
Arrays.fill(res[i], "");
}
dfs(root, res, h, 0, (n - 1) / 2);
List<List<String>> ans = new ArrayList<>();
for (String[] t : res) {
ans.add(Arrays.asList(t));
}
return ans;
}
private void dfs(TreeNode root, String[][] res, int h, int r, int c) {
if (root == null) {
return;
}
res[r][c] = String.valueOf(root.val);
dfs(root.left, res, h, r + 1, c - (1 << (h - r - 1)));
dfs(root.right, res, h, r + 1, c + (1 << (h - r - 1)));
}
private int height(TreeNode root) {
if (root == null) {
return -1;
}
return 1 + Math.max(height(root.left), height(root.right));
}
}
// Accepted solution for LeetCode #655: Print Binary Tree
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func printTree(root *TreeNode) [][]string {
var height func(root *TreeNode) int
height = func(root *TreeNode) int {
if root == nil {
return -1
}
return 1 + max(height(root.Left), height(root.Right))
}
h := height(root)
m, n := h+1, (1<<(h+1))-1
ans := make([][]string, m)
for i := range ans {
ans[i] = make([]string, n)
for j := range ans[i] {
ans[i][j] = ""
}
}
var dfs func(root *TreeNode, r, c int)
dfs = func(root *TreeNode, r, c int) {
if root == nil {
return
}
ans[r][c] = strconv.Itoa(root.Val)
dfs(root.Left, r+1, c-int(math.Pow(float64(2), float64(h-r-1))))
dfs(root.Right, r+1, c+int(math.Pow(float64(2), float64(h-r-1))))
}
dfs(root, 0, (n-1)/2)
return ans
}
# Accepted solution for LeetCode #655: Print Binary Tree
# 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
// Accepted solution for LeetCode #655: Print Binary Tree
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
fn get_height(root: &Option<Rc<RefCell<TreeNode>>>, h: u32) -> u32 {
if let Some(node) = root {
let node = node.borrow();
return Self::get_height(&node.left, h + 1).max(Self::get_height(&node.right, h + 1));
}
h - 1
}
fn dfs(
root: &Option<Rc<RefCell<TreeNode>>>,
i: usize,
j: usize,
res: &mut Vec<Vec<String>>,
height: u32,
) {
if root.is_none() {
return;
}
let node = root.as_ref().unwrap().borrow();
res[i][j] = node.val.to_string();
Self::dfs(
&node.left,
i + 1,
j - (2usize).pow(height - (i as u32) - 1),
res,
height,
);
Self::dfs(
&node.right,
i + 1,
j + (2usize).pow(height - (i as u32) - 1),
res,
height,
);
}
pub fn print_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<String>> {
let height = Self::get_height(&root, 0);
let m = (height + 1) as usize;
let n = (2usize).pow(height + 1) - 1;
let mut res = vec![vec![String::new(); n]; m];
Self::dfs(&root, 0, (n - 1) >> 1, &mut res, height);
res
}
}
// Accepted solution for LeetCode #655: Print Binary Tree
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function printTree(root: TreeNode | null): string[][] {
const getHeight = (root: TreeNode | null, h: number) => {
if (root == null) {
return h - 1;
}
return Math.max(getHeight(root.left, h + 1), getHeight(root.right, h + 1));
};
const height = getHeight(root, 0);
const m = height + 1;
const n = 2 ** (height + 1) - 1;
const res: string[][] = Array.from({ length: m }, () => new Array(n).fill(''));
const dfs = (root: TreeNode | null, i: number, j: number) => {
if (root === null) {
return;
}
const { val, left, right } = root;
res[i][j] = val + '';
dfs(left, i + 1, j - 2 ** (height - i - 1));
dfs(right, i + 1, j + 2 ** (height - i - 1));
};
dfs(root, 0, (n - 1) >>> 1);
return res;
}
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.