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.
C++
// C++ code to print Binary Tree in 2D// using Inorder Traversal#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to find the height of the binary treeintfindHeight(Node*root){if(!root){return-1;}intleftHeight=findHeight(root->left);intrightHeight=findHeight(root->right);returnmax(leftHeight,rightHeight)+1;}// Helper function to perform inorder traversal and// populate the 2D matrixvoidinorder(Node*root,introw,intcol,intheight,vector<vector<string>>&ans){if(!root){return;}// Calculate offset for child positionsintoffset=pow(2,height-row-1);// Traverse the left subtreeif(root->left){inorder(root->left,row+1,col-offset,height,ans);}// Place the current node's value in the matrixans[row][col]=to_string(root->data);// Traverse the right subtreeif(root->right){inorder(root->right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixvector<vector<string>>treeToMatrix(Node*root){// Find the height of the treeintheight=findHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1introws=height+1;intcols=pow(2,height+1)-1;// Initialize 2D matrix with empty stringsvector<vector<string>>ans(rows,vector<string>(cols,""));// Populate the matrix using inorder traversalinorder(root,0,(cols-1)/2,height,ans);returnans;}voidprint2DArray(vector<vector<string>>&arr){for(auto&row:arr){for(auto&cell:row){if(cell.empty()){cout<<" ";}else{cout<<cell;}}cout<<endl;}}intmain(){// Hardcoded binary tree// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->right->left=newNode(4);root->right->right=newNode(5);vector<vector<string>>result=treeToMatrix(root);print2DArray(result);return0;}
Java
// Java code to print Binary Tree in 2D using // Inorder Traversalimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to find the height of the binary treestaticintfindHeight(Noderoot){if(root==null){return-1;}intleftHeight=findHeight(root.left);intrightHeight=findHeight(root.right);returnMath.max(leftHeight,rightHeight)+1;}// Helper function to perform inorder traversal and// populate the 2D matrixstaticvoidinorder(Noderoot,introw,intcol,intheight,List<List<String>>ans){if(root==null){return;}// Calculate offset for child positionsintoffset=(int)Math.pow(2,height-row-1);// Traverse the left subtreeif(root.left!=null){inorder(root.left,row+1,col-offset,height,ans);}// Place the current node's value in the matrixans.get(row).set(col,String.valueOf(root.data));// Traverse the right subtreeif(root.right!=null){inorder(root.right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixstaticList<List<String>>treeToMatrix(Noderoot){// Find the height of the treeintheight=findHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1introws=height+1;intcols=(int)Math.pow(2,height+1)-1;// Initialize 2D matrix with empty stringsList<List<String>>ans=newArrayList<>();for(inti=0;i<rows;i++){List<String>row=newArrayList<>(Collections.nCopies(cols,""));ans.add(row);}// Populate the matrix using inorder traversalinorder(root,0,(cols-1)/2,height,ans);returnans;}// Function to print a 2D matrixstaticvoidprint2DArray(List<List<String>>arr){for(List<String>row:arr){for(Stringcell:row){if(cell.isEmpty()){System.out.print(" ");}else{System.out.print(cell);}}System.out.println();}}publicstaticvoidmain(String[]args){// Hardcoded binary tree// 1// / \ // 2 3 // / \ // 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);List<List<String>>result=treeToMatrix(root);print2DArray(result);}}
Python
# Python code to print Binary Tree in 2D using # Inorder TraversalclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to find the height of the binary treedeffind_height(root):ifnotroot:return-1left_height=find_height(root.left)right_height=find_height(root.right)returnmax(left_height,right_height)+1# Helper function to perform inorder traversal # and populate the 2D matrixdefinorder(root,row,col,height,ans):ifnotroot:return# Calculate offset for child positionsoffset=2**(height-row-1)# Traverse the left subtreeifroot.left:inorder(root.left,row+1,col-offset,height,ans)# Place the current node's value in the matrixans[row][col]=str(root.data)# Traverse the right subtreeifroot.right:inorder(root.right,row+1,col+offset,height,ans)# Function to convert the binary tree to a 2D matrixdeftree_to_matrix(root):# Find the height of the treeheight=find_height(root)# Rows are height + 1; columns are 2^(height+1) - 1rows=height+1cols=2**(height+1)-1# Initialize 2D matrix with empty stringsans=[[""for_inrange(cols)]for_inrange(rows)]# Populate the matrix using inorder traversalinorder(root,0,(cols-1)//2,height,ans)returnans# Function to print a 2D matrixdefprint_2d_array(arr):forrowinarr:forcellinrow:ifcell=="":print(" ",end="")else:print(cell,end="")print()if__name__=="__main__":# Hardcoded binary tree# 1# / \ # 2 3 # / \ # 4 5 root=Node(1)root.left=Node(2)root.right=Node(3)root.right.left=Node(4)root.right.right=Node(5)result=tree_to_matrix(root)print_2d_array(result)
C#
// C# code to print Binary Tree in 2D using// Inorder TraversalusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to find the height of the binary treestaticintFindHeight(Noderoot){if(root==null){return-1;}intleftHeight=FindHeight(root.left);intrightHeight=FindHeight(root.right);returnMath.Max(leftHeight,rightHeight)+1;}// Helper function to perform inorder traversal and// populate the 2D matrixstaticvoidInorder(Noderoot,introw,intcol,intheight,List<List<string>>ans){if(root==null){return;}// Calculate offset for child positionsintoffset=(int)Math.Pow(2,height-row-1);// Traverse the left subtreeif(root.left!=null){Inorder(root.left,row+1,col-offset,height,ans);}// Place the current node's value in the matrixans[row][col]=root.data.ToString();// Traverse the right subtreeif(root.right!=null){Inorder(root.right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixstaticList<List<string>>TreeToMatrix(Noderoot){// Find the height of the treeintheight=FindHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1introws=height+1;intcols=(int)Math.Pow(2,height+1)-1;// Initialize 2D matrix with empty stringsList<List<string>>ans=newList<List<string>>();for(inti=0;i<rows;i++){ans.Add(newList<string>(newstring[cols]));}// Populate the matrix using inorder traversalInorder(root,0,(cols-1)/2,height,ans);returnans;}// Function to print a 2D matrixstaticvoidPrint2DArray(List<List<string>>arr){foreach(varrowinarr){foreach(varcellinrow){if(string.IsNullOrEmpty(cell)){Console.Write(" ");}else{Console.Write(cell);}}Console.WriteLine();}}staticvoidMain(string[]args){// Hardcoded binary tree// 1// / \ // 2 3// / \ // 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);List<List<string>>result=TreeToMatrix(root);Print2DArray(result);}}
JavaScript
// JavaScript code to print Binary Tree in 2D // using Inorder Traversal// Node class for the binary treeclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to find the height of the binary treefunctionfindHeight(root){if(!root){return-1;}letleftHeight=findHeight(root.left);letrightHeight=findHeight(root.right);returnMath.max(leftHeight,rightHeight)+1;}// Helper function to perform inorder traversal // and populate the 2D matrixfunctioninorder(root,row,col,height,ans){if(!root){return;}// Calculate offset for child positionsletoffset=Math.pow(2,height-row-1);// Traverse the left subtreeif(root.left){inorder(root.left,row+1,col-offset,height,ans);}// Place the current node's value in the matrixans[row][col]=root.data.toString();// Traverse the right subtreeif(root.right){inorder(root.right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixfunctiontreeToMatrix(root){// Find the height of the treeletheight=findHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1letrows=height+1;letcols=Math.pow(2,height+1)-1;// Initialize 2D matrix with empty stringsletans=Array.from({length:rows},()=>Array(cols).fill(""));// Populate the matrix using inorder traversalinorder(root,0,Math.floor((cols-1)/2),height,ans);returnans;}// Function to print a 2D matrixfunctionprint2DArray(arr){arr.forEach(row=>{console.log(row.map(cell=>cell===""?" ":cell).join(""));});}// Hardcoded binary tree// 1// / \ // 2 3 // / \ // 4 5 letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);letresult=treeToMatrix(root);print2DArray(result);
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.
C++
// C++ code to print Binary Tree in 2D// using Preorder Traversal#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to find the height of the binary treeintfindHeight(Node*root){if(!root){return-1;}intleftHeight=findHeight(root->left);intrightHeight=findHeight(root->right);returnmax(leftHeight,rightHeight)+1;}// Helper function to perform preorder traversal and// populate the 2D matrixvoidpreorder(Node*root,introw,intcol,intheight,vector<vector<string>>&ans){if(!root){return;}// Place the current node's value in the matrixans[row][col]=to_string(root->data);// Calculate offset for child positionsintoffset=pow(2,height-row-1);// Traverse the left subtreeif(root->left){preorder(root->left,row+1,col-offset,height,ans);}// Traverse the right subtreeif(root->right){preorder(root->right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixvector<vector<string>>treeToMatrix(Node*root){// Find the height of the treeintheight=findHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1introws=height+1;intcols=pow(2,height+1)-1;// Initialize 2D matrix with empty stringsvector<vector<string>>ans(rows,vector<string>(cols,""));// Populate the matrix using preorder traversalpreorder(root,0,(cols-1)/2,height,ans);returnans;}voidprint2DArray(vector<vector<string>>&arr){for(auto&row:arr){for(auto&cell:row){if(cell.empty()){cout<<" ";}else{cout<<cell;}}cout<<endl;}}intmain(){// Hardcoded binary tree// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->right->left=newNode(4);root->right->right=newNode(5);vector<vector<string>>result=treeToMatrix(root);print2DArray(result);return0;}
Java
// Java code to print Binary Tree in 2D using // Preorder Traversalimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to find the height of the binary treestaticintfindHeight(Noderoot){if(root==null){return-1;}intleftHeight=findHeight(root.left);intrightHeight=findHeight(root.right);returnMath.max(leftHeight,rightHeight)+1;}// Helper function to perform preorder traversal and// populate the 2D matrixstaticvoidpreorder(Noderoot,introw,intcol,intheight,List<List<String>>ans){if(root==null){return;}// Place the current node's value in the matrixans.get(row).set(col,String.valueOf(root.data));// Calculate offset for child positionsintoffset=(int)Math.pow(2,height-row-1);// Traverse the left subtreeif(root.left!=null){preorder(root.left,row+1,col-offset,height,ans);}// Traverse the right subtreeif(root.right!=null){preorder(root.right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixstaticList<List<String>>treeToMatrix(Noderoot){// Find the height of the treeintheight=findHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1introws=height+1;intcols=(int)Math.pow(2,height+1)-1;// Initialize 2D matrix with empty stringsList<List<String>>ans=newArrayList<>();for(inti=0;i<rows;i++){List<String>row=newArrayList<>(Collections.nCopies(cols,""));ans.add(row);}// Populate the matrix using preorder traversalpreorder(root,0,(cols-1)/2,height,ans);returnans;}staticvoidprint2DArray(List<List<String>>arr){for(List<String>row:arr){for(Stringcell:row){if(cell.isEmpty()){System.out.print(" ");}else{System.out.print(cell);}}System.out.println();}}publicstaticvoidmain(String[]args){// Hardcoded binary tree// 1// / \ // 2 3 // / \ // 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);List<List<String>>result=treeToMatrix(root);print2DArray(result);}}
Python
# Python code to print Binary Tree in 2D using # Preorder TraversalclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to find the height of the binary treedeffind_height(root):ifnotroot:return-1left_height=find_height(root.left)right_height=find_height(root.right)returnmax(left_height,right_height)+1# Helper function to perform preorder traversal # and populate the 2D matrixdefpreorder(root,row,col,height,ans):ifnotroot:return# Place the current node's value in the matrixans[row][col]=str(root.data)# Calculate offset for child positionsoffset=2**(height-row-1)# Traverse the left subtreeifroot.left:preorder(root.left,row+1,col-offset,height,ans)# Traverse the right subtreeifroot.right:preorder(root.right,row+1,col+offset,height,ans)# Function to convert the binary tree to a 2D matrixdeftree_to_matrix(root):# Find the height of the treeheight=find_height(root)# Rows are height + 1; columns are 2^(height+1) - 1rows=height+1cols=2**(height+1)-1# Initialize 2D matrix with empty stringsans=[[""for_inrange(cols)]for_inrange(rows)]# Populate the matrix using preorder traversalpreorder(root,0,(cols-1)//2,height,ans)returnansdefprint_2d_array(arr):forrowinarr:forcellinrow:ifcell=="":print(" ",end="")else:print(cell,end="")print()if__name__=="__main__":# Hardcoded binary tree# 1# / \ # 2 3 # / \ # 4 5 root=Node(1)root.left=Node(2)root.right=Node(3)root.right.left=Node(4)root.right.right=Node(5)result=tree_to_matrix(root)print_2d_array(result)
C#
// C# code to print Binary Tree in 2D using// Preorder TraversalusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to find the height of the binary treestaticintFindHeight(Noderoot){if(root==null){return-1;}intleftHeight=FindHeight(root.left);intrightHeight=FindHeight(root.right);returnMath.Max(leftHeight,rightHeight)+1;}// Helper function to perform preorder traversal// and populate the 2D matrixstaticvoidPreorder(Noderoot,introw,intcol,intheight,List<List<string>>ans){if(root==null){return;}// Place the current node's value in the matrixans[row][col]=root.data.ToString();// Calculate offset for child positionsintoffset=(int)Math.Pow(2,height-row-1);// Traverse the left subtreeif(root.left!=null){Preorder(root.left,row+1,col-offset,height,ans);}// Traverse the right subtreeif(root.right!=null){Preorder(root.right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixstaticList<List<string>>TreeToMatrix(Noderoot){// Find the height of the treeintheight=FindHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1introws=height+1;intcols=(int)Math.Pow(2,height+1)-1;// Initialize 2D matrix with empty stringsList<List<string>>ans=newList<List<string>>();for(inti=0;i<rows;i++){ans.Add(newList<string>(newstring[cols]));}// Populate the matrix using preorder traversalPreorder(root,0,(cols-1)/2,height,ans);returnans;}staticvoidPrint2DArray(List<List<string>>arr){foreach(varrowinarr){foreach(varcellinrow){if(string.IsNullOrEmpty(cell)){Console.Write(" ");}else{Console.Write(cell);}}Console.WriteLine();}}staticvoidMain(string[]args){// Hardcoded binary tree// 1// / \ // 2 3// / \ // 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);List<List<string>>result=TreeToMatrix(root);Print2DArray(result);}}
JavaScript
// JavaScript code to print Binary Tree in 2D// using Preorder Traversal// Node class for the binary treeclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to find the height of the binary treefunctionfindHeight(root){if(!root){return-1;}letleftHeight=findHeight(root.left);letrightHeight=findHeight(root.right);returnMath.max(leftHeight,rightHeight)+1;}// Helper function to perform preorder traversal// and populate the 2D matrixfunctionpreorder(root,row,col,height,ans){if(!root){return;}// Place the current node's value in the matrixans[row][col]=root.data.toString();// Calculate offset for child positionsletoffset=Math.pow(2,height-row-1);// Traverse the left subtreeif(root.left){preorder(root.left,row+1,col-offset,height,ans);}// Traverse the right subtreeif(root.right){preorder(root.right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixfunctiontreeToMatrix(root){// Find the height of the treeletheight=findHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1letrows=height+1;letcols=Math.pow(2,height+1)-1;// Initialize 2D matrix with empty stringsletans=Array.from({length:rows},()=>Array(cols).fill(""));// Populate the matrix using preorder traversalpreorder(root,0,Math.floor((cols-1)/2),height,ans);returnans;}functionprint2DArray(arr){arr.forEach(row=>{console.log(row.map(cell=>cell===""?" ":cell).join(""));});}// Hardcoded binary tree// 1// / \ // 2 3// / \ // 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);letresult=treeToMatrix(root);print2DArray(result);
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.
C++
// C++ code to print Binary Tree in 2D // using Level Order Traversal#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to find the height of the binary treeintfindHeight(Node*root){if(!root){return-1;}intleftHeight=findHeight(root->left);intrightHeight=findHeight(root->right);returnmax(leftHeight,rightHeight)+1;}// Helper function to perform level order traversal and// populate the 2D matrixvoidlevelOrder(Node*root,introw,intcol,intheight,vector<vector<string>>&ans){if(!root){return;}// Place the current node's value in the matrixans[row][col]=to_string(root->data);// Calculate offset for child positionsintoffset=pow(2,height-row-1);// Traverse the left subtreeif(root->left){levelOrder(root->left,row+1,col-offset,height,ans);}// Traverse the right subtreeif(root->right){levelOrder(root->right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixvector<vector<string>>treeToMatrix(Node*root){// Find the height of the treeintheight=findHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1introws=height+1;intcols=pow(2,height+1)-1;// Initialize 2D matrix with empty stringsvector<vector<string>>ans(rows,vector<string>(cols,""));// Populate the matrix using level order traversallevelOrder(root,0,(cols-1)/2,height,ans);returnans;}voidprint2DArray(vector<vector<string>>&arr){for(auto&row:arr){for(auto&cell:row){if(cell.empty()){cout<<" ";}else{cout<<cell;}}cout<<endl;}}intmain(){// Hardcoded binary tree// 1// / \ // 2 3 // / \ // 4 5 Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->right->left=newNode(4);root->right->right=newNode(5);vector<vector<string>>result=treeToMatrix(root);print2DArray(result);return0;}
Java
// Java code to print Binary Tree in 2D using // Level Order Traversalimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to find the height of the binary treestaticintfindHeight(Noderoot){if(root==null){return-1;}intleftHeight=findHeight(root.left);intrightHeight=findHeight(root.right);returnMath.max(leftHeight,rightHeight)+1;}// Helper function to perform level order traversal and// populate the 2D matrixstaticvoidlevelOrder(Noderoot,introw,intcol,intheight,List<List<String>>ans){if(root==null){return;}// Place the current node's value in the matrixans.get(row).set(col,String.valueOf(root.data));// Calculate offset for child positionsintoffset=(int)Math.pow(2,height-row-1);// Traverse the left subtreeif(root.left!=null){levelOrder(root.left,row+1,col-offset,height,ans);}// Traverse the right subtreeif(root.right!=null){levelOrder(root.right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixstaticList<List<String>>treeToMatrix(Noderoot){// Find the height of the treeintheight=findHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1introws=height+1;intcols=(int)Math.pow(2,height+1)-1;// Initialize 2D matrix with empty stringsList<List<String>>ans=newArrayList<>();for(inti=0;i<rows;i++){List<String>row=newArrayList<>(Collections.nCopies(cols,""));ans.add(row);}// Populate the matrix using level order traversallevelOrder(root,0,(cols-1)/2,height,ans);returnans;}staticvoidprint2DArray(List<List<String>>arr){for(List<String>row:arr){for(Stringcell:row){if(cell.isEmpty()){System.out.print(" ");}else{System.out.print(cell);}}System.out.println();}}publicstaticvoidmain(String[]args){// Hardcoded binary tree// 1// / \ // 2 3 // / \ // 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);List<List<String>>result=treeToMatrix(root);print2DArray(result);}}
Python
# Python code to print Binary Tree in 2D using # Level Order TraversalclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to find the height of the binary treedeffind_height(root):ifnotroot:return-1left_height=find_height(root.left)right_height=find_height(root.right)returnmax(left_height,right_height)+1# Helper function to perform level order traversal # and populate the 2D matrixdeflevel_order(root,row,col,height,ans):ifnotroot:return# Place the current node's value in the matrixans[row][col]=str(root.data)# Calculate offset for child positionsoffset=2**(height-row-1)# Traverse the left subtreeifroot.left:level_order(root.left,row+1,col-offset,height,ans)# Traverse the right subtreeifroot.right:level_order(root.right,row+1,col+offset,height,ans)# Function to convert the binary tree to a 2D matrixdeftree_to_matrix(root):# Find the height of the treeheight=find_height(root)# Rows are height + 1; columns are 2^(height+1) - 1rows=height+1cols=2**(height+1)-1# Initialize 2D matrix with empty stringsans=[[""for_inrange(cols)]for_inrange(rows)]# Populate the matrix using level order traversallevel_order(root,0,(cols-1)//2,height,ans)returnansdefprint_2d_array(arr):forrowinarr:forcellinrow:ifcell=="":print(" ",end="")else:print(cell,end="")print()if__name__=="__main__":# Hardcoded binary tree# 1# / \ # 2 3 # / \ # 4 5 root=Node(1)root.left=Node(2)root.right=Node(3)root.right.left=Node(4)root.right.right=Node(5)result=tree_to_matrix(root)print_2d_array(result)
C#
// C# code to print Binary Tree in 2D using // Level Order TraversalusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to find the height of the binary treestaticintFindHeight(Noderoot){if(root==null){return-1;}intleftHeight=FindHeight(root.left);intrightHeight=FindHeight(root.right);returnMath.Max(leftHeight,rightHeight)+1;}// Helper function to perform level order traversal // and populate the 2D matrixstaticvoidLevelOrder(Noderoot,introw,intcol,intheight,List<List<string>>ans){if(root==null){return;}// Place the current node's value in the matrixans[row][col]=root.data.ToString();// Calculate offset for child positionsintoffset=(int)Math.Pow(2,height-row-1);// Traverse the left subtreeif(root.left!=null){LevelOrder(root.left,row+1,col-offset,height,ans);}// Traverse the right subtreeif(root.right!=null){LevelOrder(root.right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixstaticList<List<string>>TreeToMatrix(Noderoot){// Find the height of the treeintheight=FindHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1introws=height+1;intcols=(int)Math.Pow(2,height+1)-1;// Initialize 2D matrix with empty stringsList<List<string>>ans=newList<List<string>>();for(inti=0;i<rows;i++){ans.Add(newList<string>(newstring[cols]));}// Populate the matrix using level order traversalLevelOrder(root,0,(cols-1)/2,height,ans);returnans;}staticvoidPrint2DArray(List<List<string>>arr){foreach(varrowinarr){foreach(varcellinrow){if(string.IsNullOrEmpty(cell)){Console.Write(" ");}else{Console.Write(cell);}}Console.WriteLine();}}staticvoidMain(string[]args){// Hardcoded binary tree// 1// / \ // 2 3 // / \ // 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);List<List<string>>result=TreeToMatrix(root);Print2DArray(result);}}
JavaScript
// JavaScript code to print Binary Tree in 2D// using Level Order Traversal// Node class for the binary treeclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to find the height of the binary treefunctionfindHeight(root){if(!root){return-1;}letleftHeight=findHeight(root.left);letrightHeight=findHeight(root.right);returnMath.max(leftHeight,rightHeight)+1;}// Helper function to perform level order traversal// and populate the 2D matrixfunctionlevelOrder(root,row,col,height,ans){if(!root){return;}// Place the current node's value in the matrixans[row][col]=root.data.toString();// Calculate offset for child positionsletoffset=Math.pow(2,height-row-1);// Traverse the left subtreeif(root.left){levelOrder(root.left,row+1,col-offset,height,ans);}// Traverse the right subtreeif(root.right){levelOrder(root.right,row+1,col+offset,height,ans);}}// Function to convert the binary tree to a 2D matrixfunctiontreeToMatrix(root){// Find the height of the treeletheight=findHeight(root);// Rows are height + 1; columns are 2^(height+1) - 1letrows=height+1;letcols=Math.pow(2,height+1)-1;// Initialize 2D matrix with empty stringsletans=Array.from({length:rows},()=>Array(cols).fill(""));// Populate the matrix using level order traversallevelOrder(root,0,Math.floor((cols-1)/2),height,ans);returnans;}// Function to print the 2D arrayfunctionprint2DArray(arr){arr.forEach(row=>{console.log(row.map(cell=>cell===""?" ":cell).join(""));});}// Hardcoded binary tree// 1// / \ // 2 3// / \ // 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);letresult=treeToMatrix(root);print2DArray(result);