VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-binary-tree-2-dimensions/

⇱ Print Binary Tree in 2-Dimensions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print Binary Tree in 2-Dimensions

Last Updated : 23 Jul, 2025

Given a Binary Tree, the task is to print the tree in a 2-dimensional layout.

Examples: 

Input:

πŸ‘ Print-Binary-Tree-in-2-Dimensions-1

Output:
1
2 3
4 5

Input:

πŸ‘ Print-Binary-Tree-in-2-Dimensions-2

Output:
1
2

Using Inorder Traversal - O(n) Time and O(n) Space

The idea is to print a binary tree in a 2D matrix format using Inorder Traversal. First, we calculate the height of the tree to determine the number of rows and columns required in the matrix. Then, we perform an Inorder Traversal, placing the node values at the appropriate positions based on the traversal order and calculating the column offsets to properly position each node. Finally, we print the matrix, ensuring that empty positions are represented as spaces.


Output
 1 
 2 3 
 4 5

Using Preorder Traversal - O(n) Time and O(n) Space

The idea is to represent a binary tree in a 2D matrix format using a preorder traversal. First, we calculate the tree's height, then recursively traverse the tree, placing each node's value at the correct row and column in the matrix. The column positions are adjusted based on the height of the tree to ensure that each node's left and right children are placed correctly. The matrix is then printed.


Output
 1 
 2 3 
 4 5

Using Level Order Traversal - O(n) Time and O(n) Space

The idea is to represent a binary tree in a 2D matrix format using a level order traversal. We first calculate the height of the tree, then traverse the tree level by level, placing each node’s value in the appropriate position in the matrix. The matrix is structured such that the root is centered in the top row, and child nodes are placed at calculated offsets based on the tree height. Finally, the matrix is printed.


Output
 1 
 2 3 
 4 5
Comment
Article Tags:
Article Tags: