655. Print Binary Tree
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The core challenge of this problem is to represent a given binary tree in a 2D string matrix according to specific formatting rules. The dimensions of the matrix are determined by the tree's height. The placement of each node follows a recursive pattern: a node is placed in the middle of its designated horizontal space, and its left and right subtrees are then placed in the left and right halves of that space, respectively, on the next level down.
Solution
Print Binary Tree in Python
# 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]]:
# Helper function to calculate the height of the tree.
# Height of a null tree is -1.
def get_height(node):
if not node:
return -1
return 1 + max(get_height(node.left), get_height(node.right))
# Helper function to recursively fill the matrix.
def fill(node, r, c_start, c_end):
if not node:
return
# Calculate the middle column for the current node.
c_mid = (c_start + c_end) // 2
# Place the node's value in the matrix.
res[r][c_mid] = str(node.val)
# Recursively fill for the left and right subtrees.
fill(node.left, r + 1, c_start, c_mid - 1)
fill(node.right, r + 1, c_mid + 1, c_end)
# Step 1: Find the height of the tree.
height = get_height(root)
if height < 0:
return []
# Step 2: Calculate matrix dimensions.
rows = height + 1
cols = 2**(height + 1) - 1
# Step 3: Initialize the result matrix with empty strings.
res = [["" for _ in range(cols)] for _ in range(rows)]
# Step 4 & 5: Recursively fill the matrix.
fill(root, 0, 0, cols - 1)
# Step 6: Return the populated matrix.
return res
Print Binary Tree in Java
/**
* 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) {
// Step 1: Find the height of the tree.
int height = getHeight(root);
if (height < 0) return new ArrayList<>();
// Step 2: Calculate matrix dimensions.
int rows = height + 1;
int cols = (1 << (height + 1)) - 1;
// Step 3: Initialize the result matrix with empty strings.
List<List<String>> res = new ArrayList<>();
for (int i = 0; i < rows; i++) {
List<String> row = new ArrayList<>();
for (int j = 0; j < cols; j++) {
row.add("");
}
res.add(row);
}
// Step 4 & 5: Recursively fill the matrix.
fill(res, root, 0, 0, cols - 1);
// Step 6: Return the populated matrix.
return res;
}
// Helper function to calculate the height of the tree.
// Height of a null tree is -1.
private int getHeight(TreeNode node) {
if (node == null) {
return -1;
}
return 1 + Math.max(getHeight(node.left), getHeight(node.right));
}
// Helper function to recursively fill the matrix.
private void fill(List<List<String>> res, TreeNode node, int r, int c_start, int c_end) {
if (node == null) {
return;
}
// Calculate the middle column for the current node.
int c_mid = c_start + (c_end - c_start) / 2;
// Place the node's value in the matrix.
res.get(r).set(c_mid, String.valueOf(node.val));
// Recursively fill for the left and right subtrees.
fill(res, node.left, r + 1, c_start, c_mid - 1);
fill(res, node.right, r + 1, c_mid + 1, c_end);
}
}
Print Binary Tree in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<string>> printTree(TreeNode* root) {
// Step 1: Find the height of the tree.
int height = getHeight(root);
if (height < 0) return {};
// Step 2: Calculate matrix dimensions.
int rows = height + 1;
int cols = (1 << (height + 1)) - 1;
// Step 3: Initialize the result matrix with empty strings.
vector<vector<string>> res(rows, vector<string>(cols, ""));
// Step 4 & 5: Recursively fill the matrix.
fill(res, root, 0, 0, cols - 1);
// Step 6: Return the populated matrix.
return res;
}
private:
// Helper function to calculate the height of the tree.
// Height of a null tree is -1.
int getHeight(TreeNode* node) {
if (!node) {
return -1;
}
return 1 + max(getHeight(node->left), getHeight(node->right));
}
// Helper function to recursively fill the matrix.
void fill(vector<vector<string>>& res, TreeNode* node, int r, int c_start, int c_end) {
if (!node) {
return;
}
// Calculate the middle column for the current node.
int c_mid = c_start + (c_end - c_start) / 2;
// Place the node's value in the matrix.
res[r][c_mid] = to_string(node->val);
// Recursively fill for the left and right subtrees.
fill(res, node->left, r + 1, c_start, c_mid - 1);
fill(res, node->right, r + 1, c_mid + 1, c_end);
}
};
Print Binary Tree in TypeScript
/**
* 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[][] {
// Helper function to calculate the height of the tree.
// Height of a null tree is -1.
const getHeight = (node: TreeNode | null): number => {
if (!node) {
return -1;
}
return 1 + Math.max(getHeight(node.left), getHeight(node.right));
};
// Helper function to recursively fill the matrix.
const fill = (res: string[][], node: TreeNode | null, r: number, c_start: number, c_end: number): void => {
if (!node) {
return;
}
// Calculate the middle column for the current node.
const c_mid = c_start + Math.floor((c_end - c_start) / 2);
// Place the node's value in the matrix.
res[r][c_mid] = String(node.val);
// Recursively fill for the left and right subtrees.
fill(res, node.left, r + 1, c_start, c_mid - 1);
fill(res, node.right, r + 1, c_mid + 1, c_end);
};
// Step 1: Find the height of the tree.
const height = getHeight(root);
if (height < 0) return [];
// Step 2: Calculate matrix dimensions.
const rows = height + 1;
const cols = (1 << (height + 1)) - 1;
// Step 3: Initialize the result matrix with empty strings.
const res: string[][] = Array(rows).fill(0).map(() => Array(cols).fill(""));
// Step 4 & 5: Recursively fill the matrix.
fill(res, root, 0, 0, cols - 1);
// Step 6: Return the populated matrix.
return res;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.